开发者

Replace multiple new lines with a single newline

开发者 https://www.devze.com 2023-01-22 08:10 出处:网络
How do I replace multiple consecutive newlines with one newline. There could be up to 20 newlines next 开发者_StackOverflow中文版to each other. For example

How do I replace multiple consecutive newlines with one newline. There could be up to 20 newlines next 开发者_StackOverflow中文版to each other. For example

James said hello\n\n\n\n Test\n Test two\n\n

Should end up as:

James said hello\n Test\n Test two\n


Try this one:

$str = "Hello\n\n\n\n\nWorld\n\n\nHow\nAre\n\nYou?";
$str = preg_replace("/\n+/", "\n", $str);
print($str);


Improving on Marc B's answer:

$fixed_text  = preg_replace("\n(\s*\n)+", "\n", $text_to_fix);

Which should match an initial newline, then at least one of a group of any amount of whitespace followed by a newline and replace it all with a single newline.


$fixed_text = preg_replace("\n+", "\n", $text_to_fix);

This should do it, assuming that the consecutive newlines are truly consecutive and don't have any whitespace (tabs, spaces, carriage returns, etc...) between them.


$str = 'James said hello\n\n\n\n Test\n Test two\n\n';
echo preg_replace('{(\\\n)\1+}','$1',$str);


In regex:

  • + means "one or more of the previous expression"
  • {2,} means "two or more of the previous expression"

For the requirements in this question, there is no point replacing a single \n with a single \n because nothing changes for that substring. In other words, /\n+/ is simply doing more work than necessary.

It makes much more sense to use a ranged quantifier of two or more.

Code: (Demo)

$string = "James said hello\n\n\n\n Test\n Test two\n\n";
echo json_encode(
    preg_replace("/\n{2,}/", "\n", $string)
);

Output:

"James said hello\n Test\n Test two\n"

In other situations, it may be advantageous to replace newline sequences that may be from different operating systems with \R. This metacharacter matches \r\n or \n. Here is a modified pattern which will replace two or more newline sequences with the server's designated newline character sequence:

$string = "James\r\n said\n\r\n hello\r\n\r\n\r\n Test\n Test two\n\n";
echo json_encode(
    preg_replace("/\R{2,}/", PHP_EOL, $string)
);
// "James\r\n said\n hello\n Test\n Test two\n"
//       ^^^^----treated as one newline character sequence
0

精彩评论

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

关注公众号