On SourceForge, I downloaded a forum program named simple PHP forum and learned several text processing functions. As a result, I tried to write a simple message board with what I just learned and found the Chinese Garbled text. After solving the problem, I felt that I had learned a lot of new things. These text functions are:
- StringHtmlentities(String $ string [, int $ quote_style [, string $ charset]): converts special characters in $ string to HTML characters. "Special characters" are characters used by HTML, such as "<" and ">. If no conversion is added and output directly to the browser, the page will not display these characters or errors. Htmlentities convert them to & lt, & gt, and so on. Do not use the form to process the text before submitting it.
<? PHP
$ STR = "A 'quote' is <B> bold </B> ";
// Outputs: A 'quote' is & lt; B & gt; bold & lt;/B & gt;
Echo htmlentities ($ Str );
// Outputs: A & #039; quote & #039; is & lt; B & gt; bold & lt;/B & gt;
Echo htmlentities ($ STR, ent_quotes );
?>
- StringNl2br(String $ string): converts the line break (/n) in $ string to "<br/>" to be correctly displayed in the browser. This is also a function that is frequently used in message books and Forum programs.
- StringMysql_escape_string(String $ unescaped_string): converts $ unescaped_string to a string that can be queried using mysql_query. This is also a simple method to avoid illegal SQL statements. For example: <? PHP
$ Item = "Zak's laptop ";
$ Escaped_item = mysql_escape_string ($ item );
Printf ("% s", $ escaped_item); // output: Zak's laptop
?>
It is worth noting that htmlentities cannot properly process Chinese characters by default (that is, the last two optional parameters are omitted), and all Chinese characters are garbled. At first, I thought it was a problem with MySQL. I tried many methods and did not work. Finally, I finally got my eyes locked on htmlentities. To enable it to correctly process Chinese characters, you must specify the character encoding using the third parameter. For example, to use UTF-8 encoding, you need to write: htmlentities ($ string, ent_quotes, "UTF-8 "). For optional character sets, see http://au.php.net/manual/zh/function.htmlentities.php.
The second parameter of htmlentities specifies the conversion method of quotation marks, with three options (constant ):
- Ent_compat: Double quotation marks are converted. single quotation marks are ignored;
- Ent_quotes: Double quotation marks and single quotation marks are converted;
- Ent_noquotes: Ignore double quotation marks and single quotation marks.