“How to Determine If a PHP String Contains HTML Tags?”

You can use regular expressions or PHP’s built-in functions to check if a string contains HTML tags. Here’s an example using both approaches:

  1. Using Regular Expressions:
function containsHTMLTags($string) {
    return preg_match('/<[a-z][\s\S]*>/i', $string) === 1;
}

$string1 = "This is a plain text.";
$string2 = "This contains <b>HTML</b> tags.";

if (containsHTMLTags($string1)) {
    echo "String 1 contains HTML tags.";
} else {
    echo "String 1 does not contain HTML tags.";
}

if (containsHTMLTags($string2)) {
    echo "String 2 contains HTML tags.";
} else {
    echo "String 2 does not contain HTML tags.";
}
  1. Using strip_tags function:
function containsHTMLTags($string) {
    return $string !== strip_tags($string);
}

$string1 = "This is a plain text.";
$string2 = "This contains <b>HTML</b> tags.";

if (containsHTMLTags($string1)) {
    echo "String 1 contains HTML tags.";
} else {
    echo "String 1 does not contain HTML tags.";
}

if (containsHTMLTags($string2)) {
    echo "String 2 contains HTML tags.";
} else {
    echo "String 2 does not contain HTML tags.";
}

In both examples, the containsHTMLTags function checks if the input string contains any HTML tags. The first example uses a regular expression to find HTML tags, while the second example uses the strip_tags function to remove all HTML tags from the string and then compares the original string with the stripped version. If they are not equal, it means the original string contained HTML tags.