Home > php教程 > php手册 > php中htmlspecialchars,htmlentities用法

php中htmlspecialchars,htmlentities用法

WBOY
Release: 2016-06-13 11:19:33
Original
998 people have browsed it

在php中htmlspecialchars, 将特殊字元转成 HTML 格式,而htmlentities,将所有的字元都转成 HTML 字串 了,下面我来分别简单的介绍。  

htmlentities用法



$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'

浏览器输出:
 代码如下 复制代码

 

htmlspecialchars用法

& (和) 转成 &
" (双引号) 转成 "
> (大于) 转成 >



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

 代码如下 复制代码

 

他们的区别

这两个函数的功能都是转换字符为HTML字符编码,特别是url和代码字符串。防止字符标记被浏览器执行。使用中文时没什么区别,但htmlentities会格式化中文字符使得中文输入是乱码

htmlentities转换所有的html标记,htmlspecialchars只格式化& ' " 这几个特殊符号

 代码如下 复制代码

$str = '测试页面';

echo 'htmlentities指定GB2312编码:'.htmlentities($str,ENT_COMPAT,"GB2312").'';

echo 'htmlentities未指定编码:'.htmlentities($str).'';

$str = '测试页面';

echo htmlspecialchars($str).'';

效果:

 代码如下 复制代码

htmlentities指定GB2312编码:测试页面

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

测试页面


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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template