preg_replace返回错误的换行符


preg_replace returns wrong line break?

文本区域中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

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

你可能想要的是这个:

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

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

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