PHP的preg_replace HTML註釋我有這樣一點PHP代碼:空空間
$test = "<!--my comment goes here--> Hello World";
現在我想要去除字符串中的整個HTML註釋,我知道我需要使用的preg_replace,但現在肯定在正則表達式去那裏。 任何人都可以幫忙嗎? 感謝
PHP的preg_replace HTML註釋我有這樣一點PHP代碼:空空間
$test = "<!--my comment goes here--> Hello World";
現在我想要去除字符串中的整個HTML註釋,我知道我需要使用的preg_replace,但現在肯定在正則表達式去那裏。 任何人都可以幫忙嗎? 感謝
$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);
這是整個頁面上唯一的好答案。我也加了一個「m」修飾符。 – Damien 2011-10-07 15:20:40
<?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);
?>
preg_replace('/<!--(.*)-->/Uis', '', $html)
將會刪除在$html
字符串中的每個HTML註釋。希望這可以幫助!
當我使用此代碼時,它還會刪除顯示在2個單獨的HTML註釋塊之間的內容。我認爲U修飾符可能會使表達「貪婪」。 而不是試圖調整這一點,我用[ghostdog74的回答](https://stackoverflow.com/a/2499137/115432)中的表達,而不是有*。而不是(。*),並使用/ ms而不是/ Uis – strangerstudios 2017-11-28 14:07:15
,如果你沒有2條與評論之間像那些內容只能工作...
<!--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 im n goner」文本), – ridgerunner 2011-04-19 20:43:56
一)重複:http://stackoverflow.com/questions/2475876/php-regexto-remove-comments-but-ignore-occurances-within-strings B)最好不要做與正則表達式。 – 2010-03-23 10:31:47