我需要检测一个字符串是否包含HTML标签。
if(!preg_match('(?<=<)\w+(?=[^<]*?>)', $string)){
return $string;
}
上面的正则表达式给了我一个错误:
preg_match() [function.preg-match]: Unknown modifier '\'
我不太了解正则表达式,所以不确定问题是什么。我尝试转义 \ 但它没有做任何事情。
有比正则表达式更好的解决方案吗?如果不是,那么与 preg_match 一起使用的正确正则表达式是什么?
一个简单的解决方案是:
if($string != strip_tags($string)) {
// contains HTML
}
与正则表达式相比,它的好处是它更容易理解,但是我无法评论这两种解决方案的执行速度。
您需要用某个字符或另一个字符“分隔”正则表达式。 试试这个:
if(!preg_match('#(?<=<)\w+(?=[^<]*?>)#', $string)){
return $string;
}
如果您只想检测/替换某些标签:此函数将搜索某些 html 标签并将它们封装在括号中 - 这是相当无意义的 - 只需将其修改为您想要对标签执行的任何操作即可。
$html = preg_replace_callback(
'|\</?([a-zA-Z]+[1-6]?)(\s[^>]*)?(\s?/)?\>|',
function ($found) {
if(isset($found[1]) && in_array(
$found[1],
array('div','p','span','b','a','strong','center','br','h1','h2','h3','h4','h5','h6','hr'))
) {
return '[' . $found[0] . ']';
};
},
$html
);
正则表达式的解释:
\< ... \> //start and ends with tag brackets
\</? //can start with a slash for closing tags
([a-zA-Z]+[1-6]?) //the tag itself (for example "h1")
(\s[^>]*)? //anything such as class=... style=... etc.
(\s?/)? //allow self-closing tags such as <br />
如果目的只是检查字符串是否包含 html 标签。无论 html 标签是否有效。那你可以试试这个。
function is_html($string) {
// Check if string contains any html tags.
return preg_match('/<\s?[^\>]*\/?\s?>/i', $string);
}
这适用于所有有效或无效的 html 标签。您可以在这里检查确认https://regex101.com/r/2g7Fx4/3
我会使用
strlen()
,因为如果你不这样做,那么就会完成逐个字符的比较,这可能会很慢,尽管我希望一旦发现差异就停止比较。
我建议您仅允许定义的标签!您不希望用户键入
<script>
标签,这可能会导致 XSS 漏洞。
尝试一下:
$string = '<strong>hello</strong>';
$pattern = "/<(p|span|b|strong|i|u) ?.*>(.*)<\/(p|span|b|strong|i|u)>/"; // Allowed tags are: <p>, <span>, <b>, <strong>, <i> and <u>
preg_match($pattern, $string, $matches);
if (!empty($matches)) {
echo 'Good, you have used a HTML tag.';
}
else {
echo 'You didn\'t use a HTML tag or it is not allowed.';
}