繁体   English   中英

如何删除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 -->
我究竟做错了什么?

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

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

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

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

干杯:)

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

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

你可以不使用正则表达式来做到这一点:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM