tags:

views:

94

answers:

4

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');
+2  A: 

preg_split() should do it with

$pattern = "/(\\r\\n){2,}/";
Tomalak
yes, because pcre works "greedy" by default i.e. {2,} tries to match as many characters as possible while split() will stop the pattern matching as soon as it's fulfilled.
chendral
It didn't do it with just that, but I found the PREG_SPLIT_NO_EMPTY flag which accomplishes the same thing for my purposes.
Shadow
@chendral: Hm... @Gumbo's answer seems to indicate otherwise.
Tomalak
+1  A: 

What about the following suggestion:

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

merkuro
+1  A: 

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.

Gumbo
A: 

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

Shadow