简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM