search
Homephp教程php手册php中htmlspecialchars,htmlentities用法

php中htmlspecialchars,htmlentities用法

Jun 13, 2016 am 11:19 AM
htmlentitieshtmlspecialcharsphpexistusage

在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未指定编码:²âÊÔÒ³Ãæ

测试页面


Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool