[英]how to remove html comments in php
I am trying to remove any comments embedded with the html file我正在尝试删除嵌入在 html 文件中的任何评论
$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 -->我仍然以所有评论结束 <!- 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您可以在此处阅读: 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.我已经尝试了很多,但对我来说,这个正则表达式适用于多行(在我的例子中是 40 行注释)HTML 注释删除。
$string = preg_replace("~<!--(.*?)-->~s", "", $string);
Cheers:)干杯:)
The below regex will remove HTML comments, but will keep conditional comments.下面的正则表达式将删除 HTML 注释,但会保留条件注释。
<!--(?!<!)[^\[>].*?-->
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切换正则表达式
Regular expressions are very difficult to corral into doing what you want here.正则表达式很难在此处执行您想要的操作。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.