Home >Backend Development >PHP Tutorial >Usage of htmlspecialchars, htmlentities in php_PHP tutorial
In php, htmlspecialchars converts special characters into HTML format, while htmlentities converts all characters into HTML strings. Let me briefly introduce each of them below.
htmlentities usage
John & 'Adams'
John & 'Adams'
John & 'Adams'
The code is as follows | Copy code | ||||
|
& (and) is converted to &
" (double quotes) is converted to "
< (less than) is converted to <
Example
代码如下 | 复制代码 |
|
The code is as follows | Copy code |
|
The function of these two functions is to convert characters into HTML character encoding, especially url and code strings. Prevent character tags from being executed by the browser. There is no difference when using Chinese, but htmlentities will format Chinese characters so that Chinese input is garbled
代码如下 | 复制代码 |
$str = '测试页面'; echo 'htmlentities指定GB2312编码:'.htmlentities($str,ENT_COMPAT,"GB2312").''; echo 'htmlentities未指定编码:'.htmlentities($str).''; $str = '测试页面'; echo htmlspecialchars($str).''; |
The code is as follows | Copy code | ||||
$str = 'Test page';
echo 'htmlentities specifies GB2312 encoding: '.htmlentities($str,ENT_COMPAT,"GB2312").'';
echo 'htmlentities does not specify encoding: '.htmlentities($str).''; $str = 'Test page'; |
The code is as follows | Copy code |
htmlentities specify GB2312 encoding: test page htmlentities unspecified encoding: ²âÊÔÒ³Ãæ Test page |