2015-07-03 30 views
-3

我的服務器上有幾個文件,我只需要幫助,每當下面的HTML代碼在我的HTML中識別時,PHP函數匹配並刪除下面的代碼塊。PHP函數可以匹配HTML註釋模式並刪除HTML代碼

<!---- 728x90 Ad START ----> 
    <iframe marginheight="" marginwidth="" src="728.html" height="728" width="90" frameborder="0" scrolling="no"></iframe> 
<!---- END 728x90 Ad ----> 

<!---- 160x600 Ad START ----> 
    <iframe marginheight="" marginwidth="" src="160.html" height="160" width="600" frameborder="0" scrolling="no"></iframe> 
<!---- END 160x600 Ad ----> 


<!---- 300x250 Ad START ----> 
    <iframe marginheight="" marginwidth="" src="300.html" height="300" width="150" frameborder="0" scrolling="no"></iframe> 
<!---- END 300x250 Ad ----> 
+1

我沒有得到你到底是問什麼? – thegeekajay

+0

你能告訴我們你的PHP代碼嗎?這使我們更容易給你反饋。 – ndsmyter

+1

您是否需要刪除單詞「廣告START」和「END廣告」以及它們之間的HTML的評論? – user4035

回答

2

通常在HTML解析中使用正則表達式是一種不好的做法。但是,由於您的廣告評論具有相似的模式,因此我們可以使用正則表達式將其刪除。

<?php 
$text = ' 
<!---- 728x90 Ad START ----> 
    <iframe marginheight="" marginwidth="" src="728.html" height="728" width="90" frameborder="0" scrolling="no"></iframe> 
<!---- END 728x90 Ad ----> 

HTML code here 

<!---- 160x600 Ad START ----> 
    <iframe marginheight="" marginwidth="" src="160.html" height="160" width="600" frameborder="0" scrolling="no"></iframe> 
<!---- END 160x600 Ad ----> 

HTML code 2 here 

<!---- 300x250 Ad START ----> 
    <iframe marginheight="" marginwidth="" src="300.html" height="300" width="150" frameborder="0" scrolling="no"></iframe> 
<!---- END 300x250 Ad ----> 
'; 

//s modifier ignores newlines 
$text = preg_replace('/<!-.*?Ad START.*?Ad.*?->/s', '', $text); 
print $text; 

輸出:

HTML code here 

HTML code 2 here 

正則表達式評論

<!-  | starts with "<!-" 
.*?  | something 
Ad START | text "Ad START" 
.*?  | something 
Ad  | text "Ad" 
.*?  | something 
->  | ends with "->" 
+0

請解釋以下代碼:$ text = preg_replace('//s','',$ text); –

+1

@Ahmediqbal我評論了你的正則表達式 – user4035

+0

哇! preg_replace是一個非常強大的功能,我想我需要一些類型的循環來測試整個html代碼,對我來說非常有幫助和優雅的解決方案,非常感謝:) –