当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Reduce more than two new lines to one

问题描述:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: