Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect HTML tags in a string

Tags:

php

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?

like image 418
bcmcfc Avatar asked Apr 20 '11 15:04

bcmcfc


People also ask

How do you identify tags in HTML?

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.

How do you check if a string is HTML or not in JavaScript?

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.

How do I strip HTML tags in PHP?

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.


1 Answers

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.

like image 169
Diarmaid Avatar answered Sep 30 '22 01:09

Diarmaid