You can provide your own special markup tags for the user to use.
For example, you can allow the to use
[b]...[/b] for bolding, and
[i]...[/i]
for italics. Those would be simple string replace operations:
$output = str_replace("[b]", "<b>", $output);
$output = str_replace("[i]", "<i>", $output);
To get a little fancier, we will allow users to add links as well.
For example, the user will be allowed to enter in
[link="url"]...[/link],
which we will turn into a proper
<a href="">...</a> statement.
We can't use a simple string replace here, instead we need to use regular
expressions:
$output = ereg_replace('\[link="([[:graph:]]+)"\]', '<a href="\\1">', $output);
If you are unfamiliar with the
ereg_replace() function, this statement
means:
-
look for all occurrences of [link="..."] and replace it with <a
href="...">
[[:graph:]] means any non-whitespace character. See
the manual
for more details about regular expressions.
The
format_output() function in
outputlib.php provides
these markups and a few other ones as well. The general algorithm
would be to:
-
call htmlspecialchars() on the output text to convert all special
characters to HTML entities
-
systematically do string replacements or regexp replacements on our custom
markup tags
<?php
function format_output($output) {
/****************************************************************************
* Takes a raw string ($output) and formats it for output using a special
* stripped down markup that is similar to HTML
****************************************************************************/
$output = htmlspecialchars(stripslashes($output));
/* new paragraph */
$output = str_replace('[p]', '<p>', $output);
/* bold */
$output = str_replace('[b]', '<b>', $output);
$output = str_replace('[/b]', '</b>', $output);
/* italics */
$output = str_replace('[i]', '<i>', $output);
$output = str_replace('[/i]', '</i>', $output);
/* preformatted */
$output = str_replace('[pre]', '<pre>', $output);
$output = str_replace('[/pre]', '</pre>', $output);
/* indented blocks (blockquote) */
$output = str_replace('[indent]', '<blockquote>', $output);
$output = str_replace('[/indent]', '</blockquote>', $output);
/* anchors */
$output = ereg_replace('\[anchor=&quot;([[:graph:]]+)&quot;\]', '<a name="\1"></a>', $output);
/* links, note we try to prevent javascript in links */
$output = str_replace('[link=&quot;javascript', '[link=&quot; javascript', $output);
$output = ereg_replace('\[link=&quot;([[:graph:]]+)&quot;\]', '<a href="\1">', $output);
$output = str_replace('[/link]', '</a>', $output);
return nl2br($output);
}
?>