2

I need to split the following string and put each new line into a new array element.

this is line a.(EOL chars = '\r\n' or '\n')
(EOL chars)
this is line b.(EOL chars)
this is line c.(EOL chars)
this is the last line d.(OPTIONAL EOL chars)

(Note that the last line might not have any EOL characters present. The string also sometimes contains only 1 line, which is by definition the last one.)

The following rules must be followed:

  • Empty lines (like the second line) should be discarded and not put into the array.
  • EOL chars should not be included, because otherwise my string comparisons fail.

So this should result in the following array:

[0] => "this is line a."
[1] => "this is line b."
[2] => "this is line c."
[3] => "this is the last line d."

I tried doing the following:

$matches = array();
preg_match_all('/^(.*)$/m', $str, $matches);
return $matches[1];

$matches[1] indeed contains each new line, but:

  • Empty lines are included as well
  • It seems that a '\r' character gets smuggled in anyway at the end of the strings in the array. I suspect this has something to do with the regex range '.' which includes everything except '\n'.

Anyway, I've been playing around with '\R' and whatnot, but I just can't find a good regex pattern that follows the two rules I outlined above. Any help please?

2
  • You can just pass $matches through array_filter() ($matches = array_filter($matches);) to get rid of the empty elements. Commented Jan 11, 2012 at 13:38
  • Combining all your answers below, I found preg_split('/\R/', trim($str)); to work!!! Commented Jan 11, 2012 at 13:47

4 Answers 4

5

Just use preg_split() to split on the regular expression:

// Split on \n, \r is optional..
// The last element won't need an EOL.
$array = preg_split("/\r?\n/", $string);

Note, you might also want to trim($string) if there is a trailing newline, so you don't end up with an extra empty array element.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the trim tip. I now use preg_split('/\R/', trim($str)); which works.
preg_split('/\R+/', trim($str)) is even better now! empty lines are not included thanks to the +
3

There is a function just for this - file()

1 Comment

It's a string actually, not a file I need.
1

I think preg_split would be the way to go... You can use an appropriate regexp to use any EOL character as separator.

Something like the following (the regexp needs to be a bit more elaborate):

$array = preg_split('/[\n\r]+/', $string);

Hope that helps,

Comments

1

Use preg_split function:

$array = preg_split('/[\r\n]+/', $string);

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.