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.
精彩评论