我正在尝试清理页面上的评论,但我只想从 [code]
[/code]
标记之外的内容中删除 html 标记等.
对于标签内的内容,我只想使用 htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
。
因此,如果我有一条如下所示的评论:
<a>some text</a>
<a>some text</a>
[code]<p>some text</p>[/code]
<div>some text</div>
<div>some text</div>
[code]<p>some text</p>[/code]
<div>hfghgf</div>
<div>some text</div>
我的过滤器看起来像这样
function sanitize($data) {
$data = trim($data);
$data = strip_tags($data);
$data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
return $data;
}
现在如何使用我的 sanitize()
函数过滤 [code]
标记之外的所有内容,然后仅使用 htmlspecialchars()
[code]
标签内的内容。我还必须考虑一条评论中的多个 [code]
标签。
最佳答案
对于您的示例输入,这似乎更直接一些:
代码:(Demo)
$data=<<<HTML
<a>some text</a>
<a>some text</a>
[code]<p>some text</p>[/code]
<div>some text</div>
<div>some text</div>
[code]<p>some text</p>[/code]
<div>hfghgf</div>
<div>some text</div>
HTML;
$data=strip_tags( // strip any residual tags from the string
preg_replace_callback(
'~\[code].*?\[/code]~is', // match [code]-wrapped substrings
function($m){
return htmlspecialchars($m[0],ENT_QUOTES,'UTF-8'); // convert html entities as intended
},
$data
)
);
var_export($data);
输出:
'some text
some text
[code]<p>some text</p>[/code]
some text
some text
[code]<p>some text</p>[/code]
hfghgf
some text'
关于php - 使用一个过滤器清理 [code] 标签外部的内容,并使用另一个过滤器清理 [code] 标签内部的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49010387/