如何在php中删除html注释

时间:2012-07-05 02:54:25

标签: php html comments

我正在尝试删除嵌入了html文件的任何评论

$data= file_get_contents($stream); <br>
$data = preg_replace('<!--*-->', '', $data); <br>
echo $data;

我仍然以所有评论结束&lt; ! - bla bla bla - &gt;
我做错了什么?

8 个答案:

答案 0 :(得分:2)

以下正则表达式将删除HTML注释,但会保留条件注释。

<!--(?!<!)[^\[>].*?-->

答案 1 :(得分:2)

您可以在不使用正则表达式的情况下执行此操作:

function strip_comments($html)
{
    $html = str_replace(array("\r\n<!--", "\n<!--"), "<!--", $html);
    while(($pos = strpos($html, "<!--")) !== false)
    {
        if(($_pos = strpos($html, "-->", $pos)) === false)
            $html = substr($html, 0, $pos);
        else
            $html = substr($html, 0, $pos) . substr($html, $_pos+3);
    }
    return $html;
}

答案 2 :(得分:0)

  1. 正则表达很难在这里做你想做的事。

  2. 要匹配正则表达式中的任意文本,您需要.*,而不仅仅是*。您的表达式正在寻找<!-,后跟零个或多个-字符,然后是-->

答案 3 :(得分:0)

s/<!--[^>]*?-->//g

切换正则表达式

答案 4 :(得分:0)

我知道很多答案已经发布。我尝试了很多,但对我来说,此正则表达式适用于多行(在我的情况下为40行注释)HTML注释删除。

$string = preg_replace("~<!--(.*?)-->~s", "", $string);

干杯:)

答案 5 :(得分:0)

toString()

您可以在这里阅读:https://davidwalsh.name/remove-html-comments-php

答案 6 :(得分:0)

我不会将正则表达式用于这样的任务。正则表达式可能会因意外字符而失败。
相反,我会做一些安全的事情,就像这样:

$linesExploded = explode('-->', $html);
foreach ($linesExploded as &$line) {
    if (($pos = strpos($line, '<!--')) !== false) {
        $line = substr($line, 0, $pos);
    }
}
$html = implode('', $linesExploded);

答案 7 :(得分:-2)

你应该这样做:

$str = "<html><!-- this is a commment -->OK</html>";
$str2 = preg_replace('/<!--.*-->/s', '', $str);
var_dump($str2);