简体   繁体   English

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

[英]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值是否包含任何HTML格式,因此我可以相应地将PHPMailer电子邮件调整为HTML或纯文本。 Text looses the line feeds, if seen as 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 ";                
}

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. 有多种方法可以通过preg_matchDOMDocument使用正则表达式来执行此操作,但是有一种更简单的方法:使用strip_tags ,然后将剥离的值与未剥离的值进行比较。

// 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! 有HTML!

Boring, plain old text. 无聊的纯文本。

That has HTML! 有HTML!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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