Search code examples
phpdomxpathconditional-comments

PHP remove conditional comments which cause DOMXPath fail


conditional comments such as:

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

causes

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

does not work properly. any prepared code to remove them?


Solution

  • If parsing the HTML doesn't work then you could use regular expressions, something like this example:

    $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;
    

    Or to keep the contents of the conditional tags:

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