简体   繁体   中英

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM