How to check if string contents have any HTML in i

2020-02-09 01:14发布

How can I check if PHP string contents contain any HTML contents?

I'm not good with Regular Expressions so I would like to have a function named "is_html" to check this. :) thank you!

6条回答
【Aperson】
2楼-- · 2020-02-09 01:53

The accepted answer will consider a string containing <something> as HTML which, obviously, it is not.

I use the following, which may or may not be a better idea. (Comments appreciated.)

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

This looks for any string containing /> with zero or more letters between the slash and closing bracket.

The above function returns:

<something>             is NOT HTML
<b>foo</b>              is HTML
<B>foo</B>              is HTML
<b>foo<b>               is NOT HTML
<input />               is HTML
查看更多
Animai°情兽
3楼-- · 2020-02-09 02:00

Here's what I came up with

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

You just pass a string and check if it returns true or false. As simple as that.

查看更多
▲ chillily
4楼-- · 2020-02-09 02:02

probably the easiest way would be something like:

<?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.
查看更多
Emotional °昔
5楼-- · 2020-02-09 02:03

Instead of using regex (like the other suggestions here) I use the following method:

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

Here I use a PHP function strip_tags to remove any HTML from the string. It then compares the strings and if they do not match HTML tags were present.

查看更多
看我几分像从前
6楼-- · 2020-02-09 02:04

That depends on what you define to be html contents.

The most straightforward thing is to test if the string contains the html tag which can be done with the regex

<html.*>

In php the test will be

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

If you want to see you have valid html it's better to use a html parser.

查看更多
冷血范
7楼-- · 2020-02-09 02:16

If you want to test if a string contains a "<something>", (which is lazy but can work for you), you can try something like that :

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

Edit: You should give a look at Kevin Traas answer just below. his regex will probably return less false positive.

查看更多
登录 后发表回答