我如何为 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>
当然如果你也想处理标签中的参数的话,那么regex模式就需要做一些工作,虽然这些标签一般都没有参数。
我稍微修改了 @MrLumie 的解决方案,增加了另一个 (.?\/)?
保留 <br>
和 <br />
(尽管将它们都转换为 <br>
):
/<(\/?(strong|b|i|em|br))(.?\/)?>/i