Converting Strings to and from HTML Converting a string or an entire file into a form suitable for viewing on the Web (and vice versa) is easier than you would think. Several functions are suited for such tasks, all of which are introduced in this section. Converting Newline Characters to HTML Break Tags Thenl2br()function converts all newline (\n) characters in a string to their XHTML-compliant equivalent,<br />. Its prototype follows: string nl2br(string str) The newline characters could be created via a carriage return, or explicitly written into the string. The following example translates a text string to HTML format: <?php // convert the newlines to <br />'s. Executing this example results in the following output: -------------------------------------------- Converting Special Characters to their HTML Equivalents During the general course of communication, you may come across many characters that are not included in a document’s text encoding, or that are not readily available on the keyboard. Examples of such characters include the copyright symbol (©), the cent sign (¢), and the grave accent (è). To facilitate such shortcomings, a set of universal key codes was devised, known as character entity references. When these entities are parsed by the browser, they will be converted into their recognizable counterparts. For example, the three aforementioned characters would be presented as ©, ¢, and È, respectively. To perform these conversions, you can use thehtmlentities()function. Its prototype follows: string htmlentities(string str [, int quote_style [, int charset]]) Because of the special nature of quote marks within markup, the optionalquote_styleparameter offers the opportunity to choose how they will be handled. Three values are accepted:
A second optional parameter,charset, determines the character set used for the conversion. Table 9-2 offers the list of supported character sets. Ifcharsetis omitted, it will default toISO-8859-1.
The following example converts the necessary characters for Web display: <?php This returns the following: -------------------------------------------- Two characters are converted, the grave accent (è) and the cedilla (ç). The single quotes are ignored due to the defaultquote_stylesettingENT_COMPAT.
blog comments powered by Disqus |
|
|
|
|
|
|
|