Home > Backend Development > PHP Tutorial > Usage of htmlspecialchars, htmlentities in php_PHP tutorial

Usage of htmlspecialchars, htmlentities in php_PHP tutorial

WBOY
Release: 2016-07-20 11:03:26
Original
902 people have browsed it

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



$str = "John & 'Adams'";
echo htmlentities($str, ENT_COMPAT);
echo "
";
echo htmlentities($str, ENT_QUOTES);
echo "
";
echo htmlentities($str, ENT_NOQUOTES);
?>

John & 'Adams'
John & 'Adams'
John & 'Adams'

Browser output:
The code is as follows Copy code
 代码如下 复制代码

 

htmlspecialchars usage


& (and) is converted to &
" (double quotes) is converted to "
< (less than) is converted to <

> (greater than) is converted to >

Example


$str = "John & 'Adams'";
echo htmlspecialchars($str, ENT_COMPAT);
echo "
";
echo htmlspecialchars($str, ENT_QUOTES);
echo "
";
echo htmlspecialchars($str, ENT_NOQUOTES);
?>
 代码如下 复制代码

 

The code is as follows Copy code

Their differences

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).'';

htmlentities converts all html tags, htmlspecialchars only formats the special symbols & ' " < and >

The code is as follows Copy code
$str = 'Test page'; echo 'htmlentities specifies GB2312 encoding: '.htmlentities($str,ENT_COMPAT,"GB2312").'';
 代码如下 复制代码

htmlentities指定GB2312编码:测试页面

htmlentities未指定编码:²âÊÔÒ³Ãæ

测试页面


echo 'htmlentities does not specify encoding: '.htmlentities($str).'';

$str = 'Test page';

Effect:
The code is as follows Copy code
htmlentities specify GB2312 encoding: test page htmlentities unspecified encoding: ²âÊÔÒ³Ãæ Test page
http://www.bkjia.com/PHPjc/445287.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445287.htmlTechArticleIn php, htmlspecialchars converts special characters into HTML format, while htmlentities converts all characters into HTML strings, let me introduce them briefly below. htmlentities usage...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template