【问题标题】:PHP regular expression needed to replace line breaks, but only those between quotesPHP正则表达式需要替换换行符,但只有引号之间的
【发布时间】:2011-01-19 17:14:15
【问题描述】:

我们的客户向我们提供了需要使用 PHP 处理的 XML 数据。他们选择通过将属性用于大块文本(包含换行符)来滥用属性。 XML 解析器用空格替换换行符以使 XML W3 兼容。

为了确保我们不会丢失换行符,我想将文件作为字符串读取,然后将双引号之间的所有换行符转换为 
。我想我需要一个正则表达式,但我很难想出一个。

到目前为止,这是我的测试代码(PHP 5),使用前瞻和后视,但它不起作用:

$xml = '<tag attribute="Header\r\rFirst paragraph.">\r</tag>';
$pattern = '/(?<=")([^"]+?)\r([^"]+?)(?=")/';

print_r( preg_replace($pattern, "$1&#13;$2", $xml) );

谁能帮我解决这个问题?对于经验丰富的正则表达式大师来说应该很容易:)

【问题讨论】:

    标签: regex replace quotes


    【解决方案1】:

    没错,这就是我最终的结果。为了将来参考,我将在此处发布工作代码:

    <?php
        header("Content-Type: text/plain");
    
        $xml = '<tag attribute="Header\r\rFirst paragraph.">\r</tag>';
    
        // split the contents at the quotes
        $array = preg_split('/["]+/', $xml);
    
        // replace new lines in each of the odd strings parts
        for($i=1;$i<count($array);$i+=2){
            $array[$i] = str_replace('\n\r','&#13;',$array[$i]);
            $array[$i] = str_replace('\r\n','&#13;',$array[$i]);
            $array[$i] = str_replace('\r','&#13;',$array[$i]);
            $array[$i] = str_replace('\n','&#13;',$array[$i]);
        }
    
        // reconstruct the original string
        $xml = implode('"', $array);
    
        print_r( $xml );
    ?>
    

    感谢您回复和支持此解决方案:)

    【讨论】:

    • 也许只需将您遇到的 any 换行符替换为 &amp;#13; 就足够了?我的意思是,换行符在 XML 中(应该)无关紧要,因此您也可以替换标签之间的换行符而不会破坏任何内容。不要忘记也替换 TAB 字符。
    【解决方案2】:

    最好的方法是逐个字符搜索。如果遇到引号将布尔值设置为 true,然后在找到匹配的引号时设置为 false。

    如果你找到一个换行符,如果你在引号内(即你的变量是真的)然后“用&amp;#13;翻译”不管你的意思。否则别管它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多