我正在尝试用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'
或者双重转义CCD_ 3以引用捕获组
"/<!(--)?(?='[)(?:(?!<!'[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));
}