在php中替换多个\ r \ n

时间:2013-11-10 12:40:33

标签: php regex string

我的文字是这样的:

some text \r\n \r\n\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n some text \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n some text \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n

我需要用一个\r\n

替换多个<br/>的每个块

我尝试使用str_replace('\\r\\n','<br/>',$text);,但最终我的<br/>

太多了

我需要最终输出如下:

some text <br/> some text <br/> some text <br/>

2 个答案:

答案 0 :(得分:6)

使用带non-capturing groupquantifiers的正则表达式:

$result = preg_replace('/(?:\r\n *)+/', '<br />', $subject);

<强>说明:

(?:   # Start a group which matches:
 \r\n # one newline combination
 [ ]* # followed by zero or more spaces
)+    # Repeat the entire group once or more, as many times as possible

答案 1 :(得分:2)

使用regular expressions

$output = preg_replace(',(\r\n)+,', '<br />', $input);