2

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

<?php

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

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

echo '
​&lt;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

4

2 回答 2

1

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

你可能想要的是这样的:

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

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

于 2012-04-29T16:34:06.787 回答
0
$text_replaced = preg_replace('/^(.*) - (.*) - (.*)[' . PHP_EOL . ']$/m', '$1 - $2 "$3"', $text); 
于 2012-04-29T16:33:51.030 回答