如何在文本中检测HTML标签?

时间:2014-06-19 00:52:51

标签: php html strpos

我想看看$text值是否包含任何HTML格式,因此我可以相应地将PHPMailer电子邮件调整为HTML或纯文本。如果将文本视为HTML,则文本会丢失换行符。

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

这找不到这个。

1 个答案:

答案 0 :(得分:1)

有一些方法可以通过preg_matchDOMDocument使用正则表达式执行此操作,但有一种更简单的方法:使用strip_tags,然后将剥离值与非剥离值进行比较。< / p>

// 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 />";                
  }
}

这是上面的输出,显示了实际的概念:

  

那有HTML!

     

无聊,简单的旧文。

     

那有HTML!