PHP preg_replace html comments with empty space-ThrowExceptions

Exception or error:

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

How to solve:
$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);

Answer:

preg_replace('/<!--(.*)-->/Uis', '', $html)

Will remove every html comment contained in the $html string. Hope this helps!

Answer:

Try

 preg_replace('~<!--.+?-->~s', '', $html);

Answer:

Those will only work if you dont have 2 comments with content between like …

<!--comment--> Im a goner <!--comment-->

You need …

//preg_replace('/<!--[^>]*-->/', '', $html); // <- this is incorrect see ridgrunners comments below, you really need ...
preg_replace('/<!--.*?-->/', '', $html);

The [^>] matches anything but > so as to not go past the matching > seeking the next.
I havent tested phps regex but it claims to be perl regex which is by default ‘greedy’ and will match as much as possible.

But since youre matching a specifically named placeholder you just need the entire string and to use str_replace() instead.

str_replace('<!--my comment goes here-->', $comment, $html);

And, rather than replacing placeholders in a file just make it a php file and write out the variables.

🙂

Answer:

<?php
$test = "<!--my comment goes here--> Hello World";
echo  preg_replace('/\<.*\> / ','',$test);
?>

Use the following code for global replace:

<?php
$test = "<!--my comment goes here--> Hello World <!--------welcome-->welcome";
echo  preg_replace('/\<.*?\>/','',$test);
?>

Answer:

This should do it for you

preg_replace("/<\!--.*?-->/s","",$html);

Leave a Reply

Your email address will not be published. Required fields are marked *