检测字符串中的HTML标记

时间:2011-04-20 15:22:18

标签: php

我需要检测字符串是否包含HTML标记。

if(!preg_match('(?<=<)\w+(?=[^<]*?>)', $string)){ 
    return $string;
}

以上正则表达式给出了一个错误:

preg_match() [function.preg-match]: Unknown modifier '\'

我对正则表达式不满意所以不确定问题是什么。我试图逃避\它没有做任何事情。

有没有比正则表达更好的解决方案?如果没有,使用preg_match正确的正则表达式是什么?

8 个答案:

答案 0 :(得分:186)

一个简单的解决方案是:

if($string != strip_tags($string)) {
    // contains HTML
}

这对正则表达式的好处是它更容易理解,但我无法评论任何一种解决方案的执行速度。

答案 1 :(得分:11)

你需要用某个字符或其他字符“分隔”正则表达式。试试这个:

if(!preg_match('#(?<=<)\w+(?=[^<]*?>)#', $string)){ 
    return $string;
}

答案 2 :(得分:4)

此函数将搜索某些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 />

答案 3 :(得分:2)

我会使用strlen(),因为如果你不这样做,那么就会进行逐字符比较并且速度很慢,但我希望比较一发现差异就会退出。

答案 4 :(得分:1)

如果目的只是检查字符串是否包含html标记。无论html标签是否有效。然后你可以试试这个。

function is_html($string) {
  // Check if string contains any html tags.
  return preg_match('/<\s?[^\>]*\/?\s?>/i', $string);
}

这适用于所有有效或无效的html标记。您可以在此处查看确认IgniteSpringBean

答案 5 :(得分:0)

解析HTML一般是一个难题,这里有一些很好的材料:

但是关于你的问题('更好'的解决方案) - 可以更具体地说明你想要实现的目标,以及你可以使用哪些工具?

答案 6 :(得分:0)

如果你不擅长正则表达式(比如我),我会发现很多正则表达式库,通常可以帮助我完成任务。

这是一个explain what your trying to do in php.

的小教程

我指的是one of those libraries

答案 7 :(得分:0)

我建议您只允许使用定义的标记!您不希望用户键入<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.';
}