首页 >后端开发 >PHP问题 >PHP如何将HTML字符转义?

PHP如何将HTML字符转义?

Guanhui
Guanhui原创
2020-06-24 11:16:343249浏览

PHP如何将HTML字符转义?

PHP如何将HTML字符转义?

在PHP中可以使用“htmlspecialchars()”函数将HTML字符转义,该函数的作用是将特殊字符转换为HTML实体,其用法为“htmlspecialchars($string)”,其参数“$string”代表待转换的字符。

推荐视频教程:《PHP编程从入门到精通(学习路线)

示例

<?php
$new = htmlspecialchars("<a href=&#39;test&#39;>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>
<?php
function fixtags($text){
$text = htmlspecialchars($text);
$text = preg_replace("/=/", "=\"\"", $text);
$text = preg_replace("/&quot;/", "&quot;\"", $text);
$tags = "/&lt;(\/|)(\w*)(\ |)(\w*)([\\\=]*)(?|(\")\"&quot;\"|)(?|(.*)?&quot;(\")|)([\ ]?)(\/|)&gt;/i";
$replacement = "<$1$2$3$4$5$6$7$8$9$10>";
$text = preg_replace($tags, $replacement, $text);
$text = preg_replace("/=\"\"/", "=", $text);
return $text;
}
?>

an example:

<?php
$string = "
this is smaller < than this<br />
this is greater > than this<br />
this is the same = as this<br />
<a href=\"http://www.example.com/example.php?test=test\">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...";
echo fixtags($string);
?>

推荐教程:《PHP

以上是PHP如何将HTML字符转义?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn