PHPBuilder - Displaying Formatted User Input Page 2

RSS Twitter

Displaying Formatted User Input - Page 2

by: Ying Zhang
July 30, 2000

Formatting with Custom Markup Tags

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:
  1. call htmlspecialchars() on the output text to convert all special characters to HTML entities
  2. systematically do string replacements or regexp replacements on our custom markup tags

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]''&lt;p>'$output);

/* bold */
$output str_replace('[b]''&lt;b>'$output);
$output str_replace('[/b]''&lt;/b>'$output);

/* italics */
$output str_replace('[i]''&lt;i>'$output);
$output str_replace('[/i]''&lt;/i>'$output);

/* preformatted */
$output str_replace('[pre]''&lt;pre>'$output);
$output str_replace('[/pre]''&lt;/pre>'$output);

/* indented blocks (blockquote) */
$output str_replace('[indent]''&lt;blockquote>'$output);
$output str_replace('[/indent]''&lt;/blockquote>'$output);

/* anchors */
$output ereg_replace('\[anchor=&amp;quot;([[:graph:]]+)&amp;quot;\]''&lt;a name="\1">&lt;/a>'$output);
/* links, note we try to prevent javascript in links */
$output str_replace('[link=&amp;quot;javascript''[link=&amp;quot; javascript'$output);
$output ereg_replace('\[link=&amp;quot;([[:graph:]]+)&amp;quot;\]''&lt;a href="\1">'$output);
$output str_replace('[/link]''&lt;/a>'$output);      


« Previous Page
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Ying Zhang



(Maximum characters: 1200). You have characters left.