I need to detect whether a string contains HTML tags.
if(!preg_match('(?<=<)\w+(?=[^<]*?>)', $string)){ return $string; }
The above regex gives me an error:
preg_match() [function.preg-match]: Unknown modifier '\'
I'm not well up on regex so not sure what the problem was. I tried escaping the \ and it didn't do anything.
Is there a better solution than regex? If not, what would be the correct regex to work with the preg_match?
An HTML tag is a special word or letter surrounded by angle brackets, < and >. You use tags to create HTML elements , such as paragraphs or links. Many elements have an opening tag and a closing tag — for example, a p (paragraph) element has a <p> tag, followed by the paragraph text, followed by a closing </p> tag.
To check if a string is HTML or not with JavaScript, we check if there're any tags present in the string. const isHtml = /<\/?[a-z][\s\S]*>/i.
The strip_tags() function strips a string from HTML, XML, and PHP tags. Note: HTML comments are always stripped. This cannot be changed with the allow parameter. Note: This function is binary-safe.
A simple solution is:
if($string != strip_tags($string)) { // contains HTML }
The benefit of this over a regex is it's easier to understand, however I could not comment on the speed of execution of either solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With