如何检查字符串内容中是否有任何 HTML


How to check if string contents have any HTML in it?

如何检查PHP字符串内容是否包含任何HTML内容?

我不擅长正则表达式,所以我想有一个名为" is_html "的函数来检查这一点。 :)谢谢!

如果你想测试一个字符串是否包含一个"<something>",(这很懒,但可以为你工作),你可以尝试这样的事情:

function is_html($string)
{
  return preg_match("/<[^<]+>/",$string,$m) != 0;
}

我没有使用正则表达式(像这里的其他建议一样),而是使用以下方法:

    function isHtml($string)
    {
        if ( $string != strip_tags($string) )
        {
            return true; // Contains HTML
        }
        return false; // Does not contain HTML
    }

在这里,我使用 PHP 函数strip_tags从字符串中删除任何 HTML。然后,它会比较字符串,如果它们不匹配,则存在 HTML 标记。

接受的答案会将包含<某物>的字符串视为 HTML,显然它不是。

我使用以下方法,这可能是也可能不是更好的主意。 (感谢评论。

function isHTML( $str ) { return preg_match( "/'/[a-z]*>/i", $str ) != 0; }

这将查找包含/> 的任何字符串,斜杠和右括号之间有零个或多个字母。

上面的函数返回:

<something>             is NOT HTML
<b>foo</b>              is HTML
<B>foo</B>              is HTML
<b>foo<b>               is NOT HTML
<input />               is HTML

最简单的方法可能是:

<?php
function hasTags( $str )
{
    return !(strcmp( $str, strip_tags($str ) ) == 0);
}
$str1 = '<p>something with <a href="/some/url">html</a> in.';
$str2 = 'a string.';
var_dump( hasTags( $str1 ) ); // true - has tags.
var_dump( hasTags( $str2 ) ); // false - no tags.

这是我想到的

function isHtml($string){
     preg_match("/<'/?'w+(('s+'w+('s*='s*(?:'".*?'"|'.*?'|[^''">'s]+))?)+'s*|'s*)'/?>/",$string, $matches);
     if(count($matches)==0){
        return FALSE;
      }else{
         return TRUE;
      }
}

您只需传递一个字符串并检查它是否返回真或假。就这么简单。

这取决于你定义为 html 内容的内容。

最直接的事情是测试字符串是否包含可以使用正则表达式完成的 html 标记

<html.*>

在 php 中,测试将是

if (preg_match('/<html.*>/', $subject)) {
    # Successful match
} else {
    # Match attempt failed
}

如果你想看到你有有效的html,最好使用html解析器。