Search code examples
phphtmlregexcommentspreg-replace

PHP preg_replace html comments with empty space


I have a bit of php code like this:

$test = "<!--my comment goes here--> Hello World";

Now i want to strip the whole html comment from the string, i know i need to use preg_replace, but now sure on the regex to go in there. Can anybody help? Thanks


Solution

  • $str=<<<'EOF'
    <!--my comment goes here--> Hello World"
    blah  <!-- my another
    comment here --> blah2
    end
    EOF;
    
    $r="";
    $s=explode("-->",$str);
    foreach($s as $v){
      $m=strpos($v,'<!--');
      if($m!==FALSE){
       $r.=substr($v,1,$m);
      }
    }
    $r.=end($s);
    print $r."\n";
    

    output

    $ php test.php
    Hello World"
    blah  < blah2
    end
    

    Or if you must preg_replace,

    preg_replace("/<!--.*?-->/ms","",$str);