[英]PHP - Detect string if contains only HTML tags or text with HTML tags
I get stuck into this. 我陷入其中。 I am using WYSIWYG text editor and when I save the result into my database if the textarea is empty it stills inserts
<div><br></div>
content into my database. 我正在使用WYSIWYG文本编辑器,当将结果保存到数据库中时,如果textarea为空,它仍然将
<div><br></div>
内容插入到数据库中。 So my question is how I can identify if the string contains only HTML tags and no words? 所以我的问题是如何识别字符串是否仅包含HTML标记而没有单词? I've tried using
strpos
but with no result and I am sure that this is not the right function for doing such a check. 我已经尝试过使用
strpos
但是没有结果,而且我确信这不是进行此类检查的正确功能。
Yes it isn't the right function. 是的,这不是正确的功能。 You have to use a regex for that.
您必须为此使用正则表达式。
Here is a regex that checks if in one string, there's only html tags : 这是一个正则表达式,用于检查一个字符串中是否只有html标签:
^(<[^>]*>)+$
You can use it with the preg_match()
function of PHP like that. 可以将其与PHP的
preg_match()
函数一起使用。 This function returns true
or false
depending on if the regex is matched (if there are only HTML tags). 根据正则表达式是否匹配(如果只有HTML标记),此函数返回
true
或false
。
$is_only_html = preg_match("#^(<[^>]*>)+$#", $string_input_to_check);
Hope it helps. 希望能帮助到你。
You can use strip_tags
to check if there are only tags: 您可以使用
strip_tags
来检查是否只有标签:
if (trim(strip_tags($str)) === '') {
//only tags - no text.
}
demo: https://ideone.com/I8CPpT
演示: https : //ideone.com/I8CPpT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.