There is quite a mix of direct and indirect answers on this page and some good advice in comments, but there isn't an answer that represents what I would write in my own project.
PHP Escape Sequence \R
documentation: https://www.php.net/manual/en/regexp.reference.escape.php#:~:text=line%20break,\r\n
Code: (Demo)
$string = '
My text1
My text2
My text3
';
var_export(
preg_split('/\R+/', $string, 0, PREG_SPLIT_NO_EMPTY)
);
Output:
array (
0 => 'My text1',
1 => 'My text2',
2 => 'My text3',
)
The OP makes no mention of trimming horizontal whitespace characters from the lines, so there is no expectation of removing \s
or \h
while exploding on variable (system agnostic) new lines.
While PHP_EOL
is sensible advice, it lacks the flexibility appropriately explode the string when the newline sequence is coming from another operating system.
Using a non-regex explode will tend to be less direct because it will require string preparations. Furthermore, there may be mopping up after the the explosions if there are unwanted blank lines to remove.
Using \R+
(one or more consecutive newline sequences) and the PREG_SPLIT_NO_EMPTY
function flag will deliver a gap-less, indexed array in a single, concise function call. Some people have a bias against regular expressions, but this is a perfect case for why regex should be used. If performance is a concern for valid reasons (e.g. you are processing hundreds of thousands of points of data), then go ahead and invest in benchmarking and micro-optimization. Beyond that, just use this one-line of code so that your code is brief, robust, and direct.