开发者

Reduce more than two new lines to one

开发者 https://www.devze.com 2023-04-05 16:45 出处:网络
Whats the right way to reduce more than two new lines to one? preg_replace(\'/[\\n]{2,}/\', \"\\n\", \"Hi,\\nHow are you?\\n\\n\\nI am just testing\");

Whats the right way to reduce more than two new lines to one?

preg_replace('/[\n]{2,}/', "\n", "Hi,\nHow are you?\n\n\nI am just testing");

Returns:

开发者_如何学运维
Hi,
How are you?
I am just testing

Whilst, the expected result is:

Hi,
How are you?

I am just testing

The goal is to reformat the text of emails and change any spaces > 3 to 1

Thanks!


I'm not sure what your confusion is... Replacing 2 or more \n with one \n will result in a single line break, which is what you get. From your example, you seem want a double line break. (A line break, then an empty line, then another line break.)

preg_replace('/\n{2,}/', "\n\n", "Hi,\nHow are you?\n\n\nI am just testing");

NB that I have also removed the unnecessary [] around the \n in the regex.


Maybe this helps?

$string = str_replace("   ", "\n", $string);

or

$string = str_replace("   ", " ", $string);


Just and improvement to an a previous answer. From your example, you seem want a double line break. (A line break, then an empty line, then another line break)

preg_replace('/\n{3,}/', "\n\n", "Hi,\nHow are you?\n\n\nI am just testing");

{3,} because there is no need of matching/replacing two or less \n. NB: i posted a new answer, because i don't have the reputation to add comment yet.

0

精彩评论

暂无评论...
验证码 换一张
取 消