如何在PHP中删除HTML注释


how to remove html comments in php

我正在尝试删除嵌入在html文件中的任何注释

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

我仍然以所有评论结束<!- bla bla bla bla -->
我做错了什么?

// Remove unwanted HTML comments
function remove_html_comments($content = '') {
    return preg_replace('/<!--(.|'s)*?-->/', '', $content);
}

正如你在这里读到的:https://davidwalsh.name/remove-html-comments-php

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

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

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

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

干杯:)

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

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

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

切换正则表达式

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

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

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

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

你应该这样做:

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