在 PHP 中使用允许列表剥离标签,但删除所有属性

问题描述 投票:0回答:1

在 PHP 中,从字符串中去除所有 HTML 标记(允许列表中的标记除外)的最快、最简单的方法是什么,但通过删除所有 HTML 属性来实现。

内置函数

strip_tags
可以完成这项工作,但标签的属性保留在允许列表中。 我不知道使用正则表达式是否是最好的方法,我也不知道解析字符串是否不会贪婪。

php strip-tags
1个回答
0
投票

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>
© www.soinside.com 2019 - 2024. All rights reserved.