user7781246
user7781246

Reputation:

PHP - Detect string if contains only HTML tags or text with HTML tags

I get stuck into this. I am using WYSIWYG text editor and when I save the result into my database if the textarea is empty it stills inserts <div><br></div> content into my database. So my question is how I can identify if the string contains only HTML tags and no words? I've tried using strpos but with no result and I am sure that this is not the right function for doing such a check.

Upvotes: 1

Views: 2834

Answers (2)

secavfr
secavfr

Reputation: 953

Yes it isn't the right function. You have to use a regex for that.

Here is a regex that checks if in one string, there's only html tags :

^(<[^>]*>)+$

You can use it with the preg_match() function of PHP like that. This function returns true or false depending on if the regex is matched (if there are only HTML tags).

$is_only_html = preg_match("#^(<[^>]*>)+$#", $string_input_to_check);

Hope it helps.

Upvotes: 2

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

You can use strip_tags to check if there are only tags:

if (trim(strip_tags($str)) === '') {
    //only tags - no text.
}

demo: https://ideone.com/I8CPpT

Upvotes: 1

Related Questions