Peter Brooks
Peter Brooks

Reputation: 49

How to detect HTML tags in text?

I want to see if $text value contains any HTML formatting, so I can adjust the PHPMailer email accordingly as either HTML or plain text. Text looses the line feeds, if seen as HTML.

$email_body="<p><b>This is html code</b></p>";
$text = htmlentities($email_body); 
if (strpos($text,"<b>") !== false) {
    echo " Found a b ";                
}

This does not find this.

Upvotes: 0

Views: 1292

Answers (1)

Giacomo1968
Giacomo1968

Reputation: 26066

There are ways to do this using regex via preg_match or DOMDocument but there is an easier way: Use strip_tags and then compare the stripped value to the non-stripped value.

// Set a test array of mixed strings.
$email_body_array = array();
$email_body_array[] = "<p><b>This is html code.</b></p>";
$email_body_array[] = "This is plain text.";
$email_body_array[] = "This is a <b>bold</b> statement..";

// Now roll through the strings & test them.
foreach ($email_body_array as $email_body) {
  $email_body_stripped = strip_tags($email_body);
  $text = htmlentities($email_body); 
  if ($email_body !== $email_body_stripped) {
    echo "That has HTML!<br />";                
  }
  else {
    echo "Boring, plain old text.<br />";                
  }
}

This is the output of the above showing the concept in action:

That has HTML!

Boring, plain old text.

That has HTML!

Upvotes: 1

Related Questions