Plotoder
Plotoder

Reputation: 11

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!

Upvotes: 1

Views: 840

Answers (3)

tormuto
tormuto

Reputation: 585

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.

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 238115

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.

Upvotes: 2

Olli
Olli

Reputation: 752

Maybe this helps?

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

or

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

Upvotes: 0

Related Questions