在处理网页内容时,我们经常会遇到需要将HTML代码中的特殊字符转换成实体(如&转成&)或将HTML实体还原成普通字符的需求。PHP提供了两个非常实用的函数来完成这项工作:htmlentities 和 html_entity_decode。
本文将介绍这两个函数的基本用法,并演示如何用它们实现HTML实体的双向转换。
htmlentities 函数可以将字符串中的一些特殊字符转换为对应的HTML实体,避免浏览器将它们解析成标签或其他含义,保护页面的安全性和格式正确显示。
函数原型:
string htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] )
简单示例:
<?php
$text = "Tom & Jerry's <b>adventure</b>!";
echo htmlentities($text);
// 输出:Tom & Jerry's <b>adventure</b>!
?>
html_entity_decode 的作用正好相反,它会把HTML实体转换回对应的字符。
函数原型:
string html_entity_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") ]] )
简单示例:
<?php
$encoded = "Tom & Jerry's <b>adventure</b>!";
echo html_entity_decode($encoded);
// 输出:Tom & Jerry's <b>adventure</b>!
?>
假设我们有一段字符串,需要先转换为HTML实体保存,之后又需要将实体还原成原始字符,可以通过这两个函数结合使用实现。
<?php
$original = 'Hello & welcome to <a href="https://gitbox.net">gitbox.net</a>!';
// 将字符串转换为HTML实体
$encoded = htmlentities($original);
echo "编码后: " . $encoded . "\n";
// 再将编码后的字符串还原
$decoded = html_entity_decode($encoded);
echo "解码后: " . $decoded . "\n";
?>
输出:
编码后: Hello & welcome to <a href="https://gitbox.net">gitbox.net</a>!
解码后: Hello & welcome to <a href="https://gitbox.net">gitbox.net</a>!
flags:控制转换的实体类型,如 ENT_QUOTES 会把单引号和双引号都转换。
encoding:指定字符编码,默认是 PHP 配置中的编码,一般设置为UTF-8更安全。
double_encode(htmlentities特有):是否对已经转换过的实体再次转义,默认是true,通常设置为false避免重复编码。
用 htmlentities 可以防止HTML标签被浏览器解析,保证字符安全输出。
用 html_entity_decode 可以还原HTML实体为原始字符,方便后续处理。
双向转换结合使用,可以安全处理用户输入,防止XSS攻击,又能方便展示。
希望这篇文章能帮助你理解并应用好这两个函数,实现HTML实体的双向转换。