Replace newlines, but keep the blank lines

旧街凉风 提交于 2019-12-23 09:32:04

问题


I want to replace newlines (\r\n) with space, but I want to keep the blank lines. In other words, I want to replace \r\n with ' ', if \r\n is not preceded by another \r\n. For example:

line 1

line 2
line 3
line 4

Shold end up as...

line 1

line 2 line 3 line 4

But not as "line 1 line 2 line 3 line 4", which is what I'm doing right now with this

preg_replace("/\r\n/", " ", $string);

回答1:


Try this:

(?<!\n)\n(?!\n)

Of course, you can change \n to whatever you need.

Working example: http://ideone.com/dF5L9




回答2:


Try this:

 preg_replace("/(.)\r\n(?=.|$)/", "$1 ", $string);



回答3:


This should do the trick:

preg_replace("/(?<!\n)\n(?!\n)/", " ", $string);


来源:https://stackoverflow.com/questions/5258549/replace-newlines-but-keep-the-blank-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!