Prev | Current Page 323 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


The following example converts potentially harmful characters using
htmlspecialchars():
$input = "I just can't get <> of PHP!";
echo htmlspecialchars($input);
?>
Viewing the source, you??™ll see the following:
I just can't get <<enough>> of PHP &!
If the translation isn??™t necessary, perhaps a more efficient way to do this would be
to use strip_tags(), which deletes the tags from the string altogether.
258 CHAPTER 9 ?–  STRINGS AND REGULAR EXPRESSIONS
?– Tip If you are using gethtmlspecialchars() in conjunction with a function such as nl2br(),
you should execute nl2br() after gethtmlspecialchars(); otherwise, the
tags that are
generated with nl2br() will be converted to visible characters.
Converting Text into Its HTML Equivalent
Using get_html_translation_table() is a convenient way to translate text to its HTML
equivalent, returning one of the two translation tables (HTML_SPECIALCHARS or
HTML_ENTITIES). Its prototype follows:
array get_html_translation_table(int table [, int quote_style])
This returned value can then be used in conjunction with another predefined
function, strtr() (formally introduced later in this section), to essentially translate
the text into its corresponding HTML code.
The following sample uses get_html_translation_table() to convert text to HTML:
$string = "La pasta ?© il piatto pi?? amato in Italia";
$translate = get_html_translation_table(HTML_ENTITIES);
echo strtr($string, $translate);
?>
This returns the string formatted as necessary for browser rendering:
La pasta é il piatto piú amato in Italia
Interestingly, array_flip() is capable of reversing the text-to-HTML translation
and vice versa.


Pages:
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335