[英]PHP htmlspecialchars() or htmlentities() with exception
如何为htmlspecialchars()
或htmlentities()
定义异常? 我想将所有特殊字符转换为 HTML 安全,除了<strong><b><i><em><br>
最简单的方法是使用htmlentities
转换您的字符串,然后使用preg_replace替换选定的标签:
<?php
$string = '<p><strong>A <i>test</i> string with a <a href="#">Test link</a></strong></p>';
$encoded_string = htmlentities($string);
$encoded_string = preg_replace('/<(\/?(strong|b|i|em|br))>/', '<$1>', $encoded_string);
echo($encoded_string);
//outputs: <p><strong>A <i>test</i> string with a <a href="#">Test link</a></strong></p>
当然,如果您也想在标签内处理 arguments,那么正则表达式模式需要一些工作,尽管这些标签通常缺少任何参数。
我通过添加另一个(.?\/)?
保留<br>
和<br />
(尽管将它们都转换为<br>
):
/<(\/?(strong|b|i|em|br))(.?\/)?>/i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.