繁体   English   中英

PHP htmlspecialchars() 或 htmlentities() 例外

[英]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('/&lt;(\/?(strong|b|i|em|br))&gt;/', '<$1>', $encoded_string);

echo($encoded_string); 
//outputs: &lt;p&gt;<strong>A <i>test</i> string with a &lt;a href=&quot;#&quot;&gt;Test link&lt;/a&gt;</strong>&lt;/p&gt;

当然,如果您也想在标签内处理 arguments,那么正则表达式模式需要一些工作,尽管这些标签通常缺少任何参数。

我通过添加另一个(.?\/)? 保留<br><br /> (尽管将它们都转换为<br> ):

/&lt;(\/?(strong|b|i|em|br))(.?\/)?&gt;/i

如此处所示: https://regex101.com/r/G6D2lj/1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM