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?
$matchesthrougharray_filter()($matches = array_filter($matches);) to get rid of the empty elements.