2012-02-11 90 views
2

我想在php中編寫一個函數,它將通過mySQL數據庫循環並刪除所有條件註釋。PHP函數preg_replace多行條件註釋

我想更換看起來像這樣的文字:

<!--[if gte mso 9]><xml> <o:OfficeDocumentSettings> <o:AllowPNG /> </o:OfficeDocumentSettings> </xml><![endif]--><!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:TrackMoves /> <w:TrackFormatting /> <w:DoNotShowRevisions /> <w:DoNotPrintRevisions /> <w:DoNotShowMarkup /> <w:DoNotShowComments /> <w:DoNotShowInsertionsAndDeletions /> <w:DoNotShowPropertyChanges /> <w:PunctuationKerning /> <w:ValidateAgainstSchemas /> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:DoNotPromoteQF /><![endif]-->

這裏是我的代碼

$content = array('1' => $my_text_with_conditional_quotes) 

foreach($content as $id => $v){ 
    print $v .' <br>'; 
    $str = addcslashes(preg_replace("/<!(--)?(?=\[)(?:(?!<!\[endif\]\1>).)*<!\[endif\]\1>/s",'',$v)); 
    print $str . '<br>'; 
    print $id . '<br>'; 
    exit; 
} 

它不匹配任何東西。我錯過了什麼?

回答

1

附上你的正則表達式用單引號'

'/<!(--)?(?=\[)(?:(?!<!\[endif\]\1>).)*<!\[endif\]\1>/s' 

或雙逃脫\引用捕獲組

"/<!(--)?(?=\[)(?:(?!<!\[endif\]\\1>).)*<!\[endif\]\\1>/s" 
+0

謝謝你收到那個錯誤,現在就開始工作吧! – alockwood05 2012-02-13 18:57:10

+0

@AlexLockwood:不客氣。 – Toto 2012-02-13 19:36:01

0

從這裏將您的通配符期:1>).)*到這裏:1>)).*

此外,RegexPal是真棒測試你的正則表達式了現場,看看他們匹配的內容。

+0

好主意,但這並沒有改變結果。不過謝謝你的迴應。 – alockwood05 2012-02-13 18:59:36

0

不使用正則表達式解析XML。 你可以通過使用php字符串函數來解決這個問題。它會是這樣的:

while (1==1) { 

    $openingTagOffset = strpos($field, "<!--[if gte mso 9]>"); 
    if ($openingTagOffset === false) break; 
    $closingTag = "<![endif]-->"; 
    $closingTagOffset = strpos($field, $closingTag, $openingTagOffset); 
    $field = substr_replace($field, "", $openingTagOffset, $closingTagOffset - $openingTagOffset + strlen($closingTag)); 

} 
+0

謝謝,我喜歡一個好主意。這將幫助我更有效地解決其他問題(我認爲正則表達式使用更多的系統資源);然而,我不確定開始標籤和結束標籤是什麼,並且據我所知,正則表達式是模式匹配的方式。 – alockwood05 2012-02-13 18:58:52