Home Backend Development PHP Tutorial php htmlentities和htmlspecialchars 的区别_php技巧

php htmlentities和htmlspecialchars 的区别_php技巧

May 17, 2016 am 09:35 AM
htmlentities htmlspecialchars

The translations performed are:

复制代码 代码如下:

'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
''>' (greater than) becomes '>'

htmlspecialchars 只转化上面这几个html代码,而 htmlentities 却会转化所有的html代码,连同里面的它无法识别的中文字符也给转化了。

我们可以拿一个简单的例子来做比较:
复制代码 代码如下:

$str='测试页面';
echo htmlentities($str);
// ²âÊÔÒ³Ãæ

$str='测试页面';
echo htmlspecialchars($str);
// 测试页面

结论是,有中文的时候,最好用 htmlspecialchars ,否则可能乱码

另外参考一下这个自定义函数
复制代码 代码如下:

function my_excerpt( $html, $len ) {
// $html 应包含一个 HTML 文档。
// 本例将去掉 HTML 标记,javascript 代码
// 和空白字符。还会将一些通用的
// HTML 实体转换成相应的文本。
$search = array ("'<script>]*?>.*?</script>'si", // 去掉 javascript
"']*?>'si", // 去掉 HTML 标记
"'([\r\n])[\s]+'", // 去掉空白字符
"'&(quot|#34);'i", // 替换 HTML 实体
"'&(amp|#38);'i",
"'&(lt|#60);'i",
"'&(gt|#62);'i",
"'&(nbsp|#160);'i",
"'&(iexcl|#161);'i",
"'&(cent|#162);'i",
"'&(pound|#163);'i",
"'&(copy|#169);'i",
"'(\d+);'e"); // 作为 PHP 代码运行
$replace = array ("",
"",
"\\1",
"\"",
"&",
"">",
" ",
chr(161),
chr(162),
chr(163),
chr(169),
"chr(\\1)");
$text = preg_replace ($search, $replace, $html);
$text = trim($text);
return mb_strlen($text) >= $len ? mb_substr($text, 0, $len) : '';
}

htmlspecialchar()函数和htmlentities()函数类似都是把html代码转换,htmlspecialchars_decode是把转化的html的编码转换成转换回来。

我们可以拿一个简单的例子来做比较:
复制代码 代码如下:

$str='测试';
$transstr = htmlspecialchars($str) ;
echo $transstr . "
";
echo htmlspecialchars_decode($transstr)";

运行上面的代码,就可以看出两者的差别了。

一直都知道 PHP 中的 htmlentities 和 htmlspecialchars 函数都能把 html 中的特殊字符转换成对应的 character entity (不知道怎么翻译),也一直都知道 htmlentities 和 htmlspecialchars 函数有区别,但是一直都用不到这两个函数,也就没去研究过到底有什么区别。


今天用到了,懒得看 PHP 手册里的鸟语,觉得这种问题应该会有人用中文写过,于是 Google 关键词“htmlentities htmlspecialchars”,答案千篇一律。我已经司空见惯了,复制粘贴连小学生都会。经过对比发现,每篇文章大概都包含两部分:

第一部分是引用 PHP 手册的说明:

PHP 手册中对 htmlspecialchars 写道:

The translations performed are:
复制代码 代码如下:

‘&' (ampersand) becomes ‘&'
‘"' (double quote) becomes ‘"' when ENT_NOQUOTES is not set.
”' (single quote) becomes ‘'' only when ENT_QUOTES is set.
‘‘>' (greater than) becomes ‘>'

这部分无可厚非,但是第二部分的解释却并不怎么正确:

htmlspecialchars 只转化上面这几个html代码,而 htmlentities 却会转化所有的html代码,连同里面的它无法识别的中文字符也给转化了。

我们可以拿一个简单的例子来做比较:
复制代码 代码如下:

$str='测试页面';
echo htmlentities($str);

// ²âÊÔÒ³Ãæ

$str='测试页面';
echo htmlspecialchars($str);
// 测试页面

?>

结论是,有中文的时候,最好用 htmlspecialchars ,否则可能乱码。

难道 htmlentities 函数只有一个参数吗?当然不是!htmlentities 还有三个可选参数,分别是 $quote_style、 $charset、 $double_encode,手册对 $charset 参数是这样描述的:

Defines character set used in conversion. The default character set is ISO-8859-1.

从上面程序输出的结果判断,$str 是 GB2312 编码的,“测试页面”几个字对应的十六进制值是:

B2 E2 CA D4 D2 B3 C3 E6

然而却被当成 ISO-8859-1 编码来解析:

²âÊÔÒ³Ãæ

正好对应 HTML character entity 里的:

²âÊÔÒ³Ãæ

当然会被 htmlentities 转义掉,但是只要加上正确的编码作为参数,根本就不会出现所谓的中文乱码问题:

$str='测试页面';

echo htmlentities($str, ENT_COMPAT, 'gb2312');
// 测试页面三人成虎,以讹传讹。

结论:htmlentities 和 htmlspecialchars 的区别在于 htmlentities 会转化所有的 html character entity,而htmlspecialchars 只会转化手册上列出的几个 html character entity (也就是会影响 html 解析的那几个基本字符)。一般来说,使用 htmlspecialchars 转化掉基本字符就已经足够了,没有必要使用 htmlentities。实在要使用 htmlentities 时,要注意为第三个参数传递正确的编码。
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

HTTP Method Verification in Laravel HTTP Method Verification in Laravel Mar 05, 2025 pm 04:14 PM

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

Discover File Downloads in Laravel with Storage::download Discover File Downloads in Laravel with Storage::download Mar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

See all articles