2012-02-11 93 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