我需要检测字符串是否包含HTML标记.
if(!preg_match('(?<=<)\w+(?=[^<]*?>)', $string)){
return $string;
}
Run Code Online (Sandbox Code Playgroud)
以上正则表达式给出了一个错误:
preg_match() [function.preg-match]: Unknown modifier '\'
Run Code Online (Sandbox Code Playgroud)
我对正则表达式并不了解,所以不确定问题是什么.我试图逃避\它没有做任何事情.
有没有比正则表达式更好的解决方案?如果没有,使用preg_match的正确正则表达式是什么?
Dia*_*aid 195
一个简单的解决方案是
if($string != strip_tags($string)) {
// contains HTML
}
Run Code Online (Sandbox Code Playgroud)
这对正则表达式的好处是它更容易理解,但我无法评论任何一种解决方案的执行速度.
sim*_*mon 11
你需要用某个字符或其他字符"分隔"正则表达式.试试这个:
if(!preg_match('#(?<=<)\w+(?=[^<]*?>)#', $string)){
return $string;
}
Run Code Online (Sandbox Code Playgroud)
如果您只想检测/替换某些标签:此功能将搜索某些 html 标签并将它们封装在括号中 - 这是非常没有意义的 - 只需将其修改为您想要对标签执行的任何操作。
$html = preg_replace_callback(
'|\</?([a-zA-Z]+[1-6]?)(\s[^>]*)?(\s?/)?\>|',
function ($found) {
if(isset($found[1]) && in_array(
$found[1],
array('div','p','span','b','a','strong','center','br','h1','h2','h3','h4','h5','h6','hr'))
) {
return '[' . $found[0] . ']';
};
},
$html
);
Run Code Online (Sandbox Code Playgroud)
正则表达式的解释:
\< ... \> //start and ends with tag brackets
\</? //can start with a slash for closing tags
([a-zA-Z]+[1-6]?) //the tag itself (for example "h1")
(\s[^>]*)? //anything such as class=... style=... etc.
(\s?/)? //allow self-closing tags such as <br />
Run Code Online (Sandbox Code Playgroud)