在 PHP 中,从字符串中去除所有 HTML 标记(允许列表中的标记除外)的最快、最简单的方法是什么,但通过删除所有 HTML 属性来实现。
内置函数
strip_tags
可以完成这项工作,但标签的属性保留在允许列表中。
我不知道使用正则表达式是否是最好的方法,我也不知道解析字符串是否不会贪婪。
strip_tags
取出属性后应该比较简单。
$htmlString = '<span>777</span><div class="hello">hello <b id="12">world</b></div>';
$stripped = strip_tags($htmlString, '<div><b>');
// so: https://stackoverflow.com/a/3026235/3807365
$cleanHtmlString = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/si",'<$1$2>', $stripped);
echo $cleanHtmlString;
输出:
777<div>hello <b>world</b></div>