这是我的PHP函数,用于从字符串输入中删除所有空HTML标记:
/**
* Remove the nested HTML empty tags from the string.
*
* @param $string String to remove tags
* @param null $replaceTo Replace empty string with
* @return mixed Cleaned string
*/
function crl_remove_empty_tags($string, $replaceTo = null)
{
// Return if string not given or empty
if (!is_string($string) || trim($string) == '') return $string;
// Recursive empty HTML tags
return preg_replace(
'/<(\w+)\b(?:\s+[\w\-.:]+(?:\s*=\s*(?:"[^"]*"|"[^"]*"|[\w\-.:]+))?)*\s*/?>\s*</\1\s*>/gixsm',
!is_string($replaceTo) ? '' : $replaceTo,
$string
);
}
Run Code Online (Sandbox Code Playgroud)
我的正则表达式: /<(\w+)\b(?:\s+[\w\-.:]+(?:\s*=\s*(?:"[^"]*"|"[^"]*"|[\w\-.:]+))?)*\s*/?>\s*</\1\s*>/gixsm
我用http://gskinner.com/RegExr/和http://regexpal.com/对它进行了测试,效果很好.但是当我试图运行它时.服务器始终返回错误:
Warning: preg_replace(): Unknown modifier '\'
Run Code Online (Sandbox Code Playgroud)
我不知道'''出了什么问题.有人请帮帮我!
在php正则表达式中,如果它们在表达式中出现在字面上,则需要转义分隔符.
在你的情况下,你有两个没有转义/; 只需用它们替换它们\/.您也不需要修饰符数组 - 默认情况下,php是全局的,并且您没有定义文字字符.
之前:
/<(\w+)\b(?:\s+[\w\-.:]+(?:\s*=\s*(?:"[^"]*"|"[^"]*"|[\w\-.:]+))?)*\s*/?>\s*</\1\s*>/gixsm
Run Code Online (Sandbox Code Playgroud)
后:
/<(\w+)\b(?:\s+[\w\-.:]+(?:\s*=\s*(?:"[^"]*"|"[^"]*"|[\w\-.:]+))?)*\s*\/?>\s*<\/\1\s*>/
// ^ ^
Run Code Online (Sandbox Code Playgroud)