Several characters play a dual role in both markup languages and the human language. When used in the latter fashion, these characters must be converted into their displayable equivalents. For example, an ampersand must be converted to&, whereas a greater-than character must be converted to >. Thehtmlspecialchars()function can do this for you, converting the following characters into their compatible equivalents. Its prototype follows: string htmlspecialchars(string str [, int quote_style [, string charset]]) The list of characters thathtmlspecialchars()can convert and their resulting formats follow:
This function is particularly useful in preventing users from entering HTML markup into an interactive Web application, such as a message board. The following example converts potentially harmful characters usinghtmlspecialchars(): <?php Viewing the source, you’ll see the following: -------------------------------------------- If the translation isn’t necessary, perhaps a more efficient way to do this would be to usestrip_tags(), which deletes the tags from the string altogether. Tip If you are usinggethtmlspecialchars()in conjunction with a function such asnl2br(), you should executenl2br()aftergethtmlspecialchars(); otherwise, the<br />tags that are generated withnl2br()will be converted to visible characters.
Converting Text into Its HTML Equivalent Usingget_html_translation_table()is a convenient way to translate text to its HTML equivalent, returning one of the two translation tables (HTML_SPECIALCHARSorHTML_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 usesget_html_translation_table()to convert text to HTML: <?php This returns the string formatted as necessary for browser rendering: -------------------------------------------- Interestingly,array_flip()is capable of reversing the text-to-HTML translation and vice versa. Assume that instead of printing the result ofstrtr()in the preceding code sample, you assign it to the variable$translated_string. The next example usesarray_flip()to return a string back to its original value: <?php This returns the following: --------------------------------------------
blog comments powered by Disqus |
|
|
|
|
|
|
|