PHP转义HTML字符的方法
这篇文章运用简单易懂的例子给大家介绍PHP转义HTML字符的方法,代码非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
在PHP中可以使用“htmlspecialchars()”函数将HTML字符转义,该函数的作用是将特殊字符转换为HTML实体,其用法为“htmlspecialchars($string)”,其参数“$string”代表待转换的字符。
示例
<?php$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);echo $new; // <a href='test'>Test</a>?>
<?phpfunction fixtags($text){$text = htmlspecialchars($text);$text = preg_replace("/=/", "=\"\"", $text);$text = preg_replace("/"/", ""\"", $text);$tags = "/<(\/|)(\w*)(\ |)(\w*)([\\\=]*)(?|(\")\""\"|)(?|(.*)?"(\")|)([\ ]?)(\/|)>/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转义HTML字符的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。