Alex S
Alex S

Reputation: 26051

Regex with multiple newlines in sequence

I'm trying to use PHP's split() (preg_split() is also an option if your answer works with it) to split up a string on 2 or more \r\n's. My current effort is:

split("(\r\n){2,}",$nb);

The problem with this is it matches every time there is 2 or 3 \r\n's, then goes on and finds the next one. This is ineffective with 4 or more \r\n's.

I need all instances of two or more \r\n's to be treated the same as two \r\n's. For example, I'd need

Hello\r\n\r\nMy\r\n\r\n\r\n\r\n\r\n\r\nName is\r\nShadow

to become

array('Hello','My','Name is\r\nShadow');

Upvotes: 2

Views: 836

Answers (5)

mickmackusa
mickmackusa

Reputation: 47874

\R is shorthand for matching newline sequences across different operating systems. You can prevent empty elements being created at the start and end of your output array by using the PREG_SPLIT_NO_EMPTY flag or you could call trim() on the string before splitting.

Code: (Demo)

$string = "\r\n\r\nHello\r\n\r\nMy\r\n\r\n\r\n\r\n\r\n\r\nName is\r\nShadow\r\n\r\n\r\n\r\n";

var_export(preg_split('~\R{2,}~', $string, 0, PREG_SPLIT_NO_EMPTY));

echo "\n---\n";

var_export(preg_split('~\R{2,}~', trim($string)));

Output from either technique:

array (
  0 => 'Hello',
  1 => 'My',
  2 => 'Name is
Shadow',
)

Upvotes: 0

Alex S
Alex S

Reputation: 26051

Adding the PREG_SPLIT_NO_EMPTY flag to preg_replace() with Tomalak's pattern of "/(\\r\\n){2,}/" accomplished this for me.

Upvotes: 0

Gumbo
Gumbo

Reputation: 655169

It works for me:

$nb = "Hello\r\n\r\nMy\r\n\r\n\r\n\r\n\r\n\r\nName is\r\nShadow";
$parts = split("(\r\n){2,}",$nb);
var_dump($parts);
var_dump($parts === array('Hello','My',"Name is\r\nShadow"));

Prints:

array(3) {
  [0]=>
  string(5) "Hello"
  [1]=>
  string(2) "My"
  [2]=>
  string(15) "Name is
Shadow"
}
bool(true)

Note the double quotes in the second test to get the characters represented by \r\n.

Upvotes: 1

merkuro
merkuro

Reputation: 6167

What about the following suggestion:

$nb = implode("\r\n", array_filter(explode("\r\n", $nb)));

Upvotes: 1

Tomalak
Tomalak

Reputation: 338138

preg_split() should do it with

$pattern = "/(\\r\\n){2,}/";

Upvotes: 3

Related Questions