简体   繁体   中英

how to remove html comments in php

I am trying to remove any comments embedded with the html file

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

I am still ending up with all the comments < !- bla bla bla -->
What am I doing wrong?

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

As you can read here: https://davidwalsh.name/remove-html-comments-php

I know lots of answers are already posted. I have tried many but for me this regular expression works for multi line (in my case 40 line of comments) HTML comments removal.

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

Cheers:)

The below regex will remove HTML comments, but will keep conditional comments.

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

You could do it without using regular expression:

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

switch up regular expression

  1. Regular expressions are very difficult to corral into doing what you want here.

  2. To match arbitrary text in a regex, you need .* , not just * . Your expression is looking for <!- , followed by zero or more - characters, followed by --> .

I would not use regex for such a task. Regex can fail for unexpected characters.
Instead, I would do something that is safe, like this:

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

You should do this way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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