我正在尝试清理我页面上的评论,但我只想从[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;
}
我现在如何使用[code]
功能过滤sanitize()
标记之外的所有内容,然后仅对htmlspecialchars()
标记内的内容使用[code]
。我还必须在一条评论中考虑多个[code]
代码。
答案 0 :(得分:2)
对于您的样本输入,这似乎更直接:
代码:(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'
答案 1 :(得分:0)
我想出了解决方案。如果其他人在这里需要它,那就是。
function sanitize($data) {
$data = trim($data);
$data = strip_tags($data);
$data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
return $data;
}
$data = preg_split('/(\[code\])|(\[\/code\])/i', $data, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); // Split the array
foreach($data as $key => $value) {
if(($value === "[code]") || ($value === "[CODE]")) {
$data[$key] = $value.htmlspecialchars($data[$key+1],ENT_QUOTES, 'UTF-8').htmlspecialchars($data[$key+2], ENT_QUOTES, 'UTF-8'); // Set key with sanitized code block
unset($data[$key+1]); // Unset old key with content inside code tags
unset($data[$key+2]); // Unset old key with "[/code]"
}
}
$data = array_values($data); // Reorder the array
foreach($data as $key => $value) {
if(!preg_match("/\[code\][\s\S]*?\[\/code\]/i", $value)) {
$data[$key] = sanitize($value);
}
}
$data = implode(" ", $data);