[英]PHP function to preg_replace multi-line conditional comments
我正在嘗試在php中編寫一個函數,該函數將循環通過mySQL數據庫並刪除所有條件注釋。
我要替換的文本如下所示:
<!--[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;
}
它不匹配任何東西。 我想念什么?
將您的正則表達式用單引號引起來'
'/<!(--)?(?=\[)(?:(?!<!\[endif\]\1>).)*<!\[endif\]\1>/s'
或兩次轉義\\
以引用捕獲組
"/<!(--)?(?=\[)(?:(?!<!\[endif\]\\1>).)*<!\[endif\]\\1>/s"
將通配符期間從此處: 1>).)*
移至此處: 1>)).*
另外, RegexPal非常適合實時測試您的正則表達式,以查看其匹配項。
不要使用正則表達式來解析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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.