How to Split a PHP String by Newline?

If you know exactly which newline characters the string you wish to split uses, then you can simply use the explode() function, for example, like so:

$str = "foo\nbar\nbaz";
$arr = explode("\n", $str);

var_dump($arr); // ['foo', 'bar', 'baz']

Here, it's important to note the use of double quotes, as PHP only interprets escape sequences in a double-quoted string.

If the string has a mix of different newline characters, or you are not sure exactly which newline character(s) the string has, then you can use the following regular expression:

preg_split('/\r\n|\r|\n/', $str);

For example, such could be the case when a string is coming as a payload from a client request from potentially a different operating system than that of the server, and it could be using a different newline character. In such a case, using this regular expression would make sense:

// POST => ['str' => 'foo\r\nbar\r\nbaz']
$arr = preg_split('/\r\n|\r|\n/', $_POST['str']);

var_dump($arr); // ['foo', 'bar', 'baz']

If your string can potentially have multiple newlines before a word, then you could specify PREG_SPLIT_NO_EMPTY as the fourth argument to the preg_split() function, which would ignore any empty values:

$str =<<<STR


$arr = preg_split('/\r\n|\r|\n/', $str, -1, PREG_SPLIT_NO_EMPTY);

var_dump($arr); // ['foo', 'bar', 'baz']

If you're using PHP 8, then you can rewrite the above and use named argument for the fourth parameter. This would mean that you don't have to explicitly specify the third argument. For example:

// PHP 8+
$arr = preg_split('/\r\n|\r|\n/', $str, flags: PREG_SPLIT_NO_EMPTY);

As an alternative to using \r\n|\r|\n in a regular expression, you may also use \R escape sequence (which matches any Unicode newline sequence):

preg_split('/\R/', $str);

If the \R escape sequence does not work for you then it could be that PCRE was built with a different line ending sequence selected for \R. It is also worth mentioning that \R does not work inside a character class.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.