检测字符串中的 HTML 标签

问题描述 投票:0回答:8

我需要检测一个字符串是否包含HTML标签。

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

上面的正则表达式给了我一个错误:

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

我不太了解正则表达式,所以不确定问题是什么。我尝试转义 \ 但它没有做任何事情。

有比正则表达式更好的解决方案吗?如果不是,那么与 preg_match 一起使用的正确正则表达式是什么?

php
8个回答
230
投票

一个简单的解决方案是:

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

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


12
投票

您需要用某个字符或另一个字符“分隔”正则表达式。 试试这个:

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

6
投票

如果您只想检测/替换某些标签:此函数将搜索某些 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 />

4
投票

如果目的只是检查字符串是否包含 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


2
投票

我会使用

strlen()
,因为如果你不这样做,那么就会完成逐个字符的比较,这可能会很慢,尽管我希望一旦发现差异就停止比较。


2
投票

我建议您仅允许定义的标签!您不希望用户键入

<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.';
}

0
投票

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

这里有一个小教程,将 解释您在 php 中尝试做什么。

这是我提到的其中一个库。


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

  • 解析 Html 克苏鲁之道
  • 解析:超越正则表达式
但是关于你的问题(“更好”的解决方案) - 可以更具体地说明你想要实现的目标,以及你可以使用哪些工具?

© www.soinside.com 2019 - 2024. All rights reserved.