【问题标题】:preg_replace returns wrong line break?preg_replace 返回错误的换行符?
【发布时间】:2012-04-29 16:25:15
【问题描述】:

在文本区域中遇到 preg_replace 问题。 "$" 或 "m" 修饰符在这里不能正常工作:

<?php

$text = '1 - 2 - 3
a - b - c
foo - bar - baz';

$text_replaced = preg_replace('/^(.*) - (.*) - (.*)$/m', '$1 - $2 "$3"', $text); 

echo '
​<textarea rows=20 cols=20>
'.$text_replaced.'
</textarea>​​​​​​​​
';

应该返回

1 - 2 "3"
a - b "c"
foo - bar "baz"

但它会返回

1 - 2 "3
"
a - b "c
"
foo - bar "baz"

如何解决?

试试自己:http://codepad.viper-7.com/LqgDHg

【问题讨论】:

    标签: php preg-replace line-breaks


    【解决方案1】:

    默认情况下,. 匹配除\n (LF) 之外的所有内容。但是,您使用 Windows 样式的 \r\n (CRLF) 换行符。因此\r 包含在匹配项中。

    你可能想要的是这个:

    preg_replace('/(*ANYCRLF)^(.*) - (.*) - (.*)$/m', '$1 - $2 "$3"', $text);
    

    (*ANYCRLF) 修饰符将. 的含义更改为接受除\r\n 之外的所有字符。

    【讨论】:

      【解决方案2】:
      $text_replaced = preg_replace('/^(.*) - (.*) - (.*)[' . PHP_EOL . ']$/m', '$1 - $2 "$3"', $text); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-02
        • 1970-01-01
        • 2015-06-14
        • 2014-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-23
        相关资源
        最近更新 更多