【发布时间】:2011-02-14 20:37:33
【问题描述】:
PHP strip_tags 使用白名单来跳过一些你不想被删除的标签。任何人都知道一些实现,但使用黑名单而不是白名单?
【问题讨论】:
标签: php parsing html-parsing strip-tags
PHP strip_tags 使用白名单来跳过一些你不想被删除的标签。任何人都知道一些实现,但使用黑名单而不是白名单?
【问题讨论】:
标签: php parsing html-parsing strip-tags
一个简单的复合正则表达式搜索就可以了(如果这仍然是关于您之前的问题):
$html =
preg_replace("#</?(font|strike|marquee|blink|del)[^>]*>#i", "", $html);
【讨论】:
[^>]* 是匹配 HTML 标签内所有内容的常用方法。它匹配任意数量的非闭合>尖括号的字符。正则表达式部分[^...] 表示negated character class。
试试 LWC 在 php.net 上发布的这个功能 - http://www.php.net/manual/en/function.strip-tags.php#96483
<?php
function strip_only($str, $tags, $stripContent = false) {
$content = '';
if(!is_array($tags)) {
$tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
if(end($tags) == '') array_pop($tags);
}
foreach($tags as $tag) {
if ($stripContent)
$content = '(.+</'.$tag.'[^>]*>|)';
$str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
}
return $str;
}
$str = '<font color="red">red</font> text';
$tags = 'font';
$a = strip_only($str, $tags); // red text
$b = strip_only($str, $tags, true); // text
?>
【讨论】: