PHP 删除导致 DOMXPath 失败的条件注释


PHP remove conditional comments which cause DOMXPath fail

条件注释,例如:

<!--[if lt IE 7 ]><!--> <html lang="hi" class="ie ie6"> <!--<![endif]-->

原因

$doc->loadHTML($content);   
$xpath = new DOMXPath($doc);

无法正常工作。 是否有准备好的代码来删除它们?

如果解析 HTML 不起作用,那么您可以使用正则表达式,如以下示例所示:

$str = "aa<!--[if lt IE 7 ]><!--> <html lang='"hi'" class='"ie ie6'"> <!--<![endif]-->bb cc";
$pattern = "/(<!--[if's[lg]+t'sIE's[0-9]+'s]><!-->)(.*)(<!--<!'[endif']-->)/"; 
$str = preg_replace($pattern, '', $str);    
echo $str;

或者保留条件标记的内容:

$str = preg_replace($pattern, '$2', $str);
echo $str;