How to Check If a String Contains HTML Tags in PHP?

By Hardik Savani May 14, 2024 Category : PHP

This article is focused on how to check if a string contains html tags in php. you'll learn php check if string contains html tags. i explained simply step by step how to check string content have any html tag in php. it's simple example of check if string contains html tags php.

Sometime we need to check if a string content have html tag in php for some logic. as my requirement. i have some content have tag and some content does not have any tags i need to check because there is a https link so i need to add anchor tag for that. so i search on google and finally find out solution.

I will give you simple two example with output so you can check that.

Example 1:

<?php

$myString = "Hi Rahul, <p>This is dog.</p>, hep";

if (isHTML($myString)) {

echo "There is a HTML Tag in String";

}else{

echo "No HTML Tag in String";

}

function isHtml($string)

{

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

}

?>

Output:

There is a HTML Tag in String

Example 2:

<?php

$myString = "Hi Rahul, This is dog., hep";

if (isHTML($myString)) {

echo "There is a HTML Tag in String";

}else{

echo "No HTML Tag in String";

}

function isHtml($string)

{

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

}

?>

Output:

No HTML Tag in String

I hope it can help you...

Tags :
Shares