【发布时间】:2011-01-30 17:47:19
【问题描述】:
我有一些这样的 php 代码:
$test = "<!--my comment goes here--> Hello World";
现在我想从字符串中删除整个 html 注释,我知道我需要使用 preg_replace,但现在确定要使用正则表达式。 有人可以帮忙吗? 谢谢
【问题讨论】:
标签: php html regex comments preg-replace
我有一些这样的 php 代码:
$test = "<!--my comment goes here--> Hello World";
现在我想从字符串中删除整个 html 注释,我知道我需要使用 preg_replace,但现在确定要使用正则表达式。 有人可以帮忙吗? 谢谢
【问题讨论】:
标签: php html regex comments preg-replace
这应该会为你做的
preg_replace("/<\!--.*?-->/s","",$html);
【讨论】:
<?php
$test = "<!--my comment goes here--> Hello World";
echo preg_replace('/\<.*\> / ','',$test);
?>
使用以下代码进行全局替换:
<?php
$test = "<!--my comment goes here--> Hello World <!--------welcome-->welcome";
echo preg_replace('/\<.*?\>/','',$test);
?>
【讨论】:
只有当你没有 2 个 cmets 的内容介于...之间时,这些才会起作用。
<!--comment--> Im a goner <!--comment-->
你需要...
//preg_replace('/<!--[^>]*-->/', '', $html); // <- this is incorrect see ridgrunners comments below, you really need ...
preg_replace('/<!--.*?-->/', '', $html);
[^>] 匹配除 > 之外的任何内容,以免越过匹配的 > 寻找下一个。 我还没有测试过 phps 正则表达式,但它声称是 perl 正则表达式,默认情况下是“贪婪”的,并且会尽可能匹配。
但由于您要匹配一个专门命名的占位符,您只需要整个字符串并使用 str_replace() 代替。
str_replace('<!--my comment goes here-->', $comment, $html);
而且,与其替换文件中的占位符,不如将其变成一个 php 文件并写出变量。
:)
【讨论】:
> 是允许的,并且在评论中完全有效。在这种情况下,.*?lazy-dot-star 实际上是更好的表达方式(并且不会像您推断的那样删除 "Im a goner" 文本),
preg_replace('/<!--(.*)-->/Uis', '', $html)
将删除 $html 字符串中包含的每个 html 注释。希望这会有所帮助!
【讨论】:
$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";
输出
$ php test.php
Hello World"
blah < blah2
end
或者如果你必须 preg_replace,
preg_replace("/<!--.*?-->/ms","",$str);
【讨论】:
试试
preg_replace('~<!--.+?-->~s', '', $html);
【讨论】: