![](/img/trans.png)
[英]PHP - Detect string if contains only HTML tags or text with HTML tags
[英]How to detect HTML tags in text?
我想看看$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 ";
}
找不到此。
有多种方法可以通过preg_match
或DOMDocument
使用正则表达式来执行此操作,但是有一种更简单的方法:使用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 />";
}
}
这是上面的输出,显示了实际的概念:
有HTML!
无聊的纯文本。
有HTML!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.