2

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');

5 Answers 5

3

preg_split() should do it with

$pattern = "/(\\r\\n){2,}/";
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
@chendral: Hm... @Gumbo's answer seems to indicate otherwise.
1

What about the following suggestion:

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

Comments

1

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.

Comments

0

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

Comments

0

\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',
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.