Explode PHP string by new line

Viewed 388836

Simple, right? Well, this isn't working :-\

$skuList = explode('\n\r', $_POST['skuList']);
19 Answers

It doesn't matter what your system uses as newlines if the content might be generated outside of the system.

I am amazed after receiving all of these answers, that no one has simply advised the use of the \R escape sequence. There is only one way that I would ever consider implementing this in one of my own projects. \R provides the most succinct and direct approach.

https://www.php.net/manual/en/regexp.reference.escape.php#:~:text=line%20break:%20matches%20\n,%20\r%20and%20\r\n

Code: (Demo)

$text = "one\ntwo\r\nthree\rfour\r\n\nfive";

var_export(preg_split('~\R~', $text));

Output:

array (
  0 => 'one',
  1 => 'two',
  2 => 'three',
  3 => 'four',
  4 => '',
  5 => 'five',
)

To preserve line breaks (as blank items in the array):

$skuList = preg_split('/\r\n|\n\r|\r|\n/', $_POST['skuList']);`

This handles the unusual \n\r as well as the usual \n\r, \n and \r. Note that the solution from @Alin_Purcaru is very similar, but doesn't handle \n\r.

To remove line breaks (no blank items in the array):

$skuList = preg_split('/[\r\n]+/', $_POST['skuList']);

PHP Tests
These expressions has been tested on the following OS'es: ubuntu-20.04, ubuntu-18.04, windows-2022, windows-2019, windows-2016, macos-11, macos-10.15 and in the following PHP versions: 8.0, 7.4, 7.3, 7.2, 7.1, 7.0

Here is the PHP test class:
https://github.com/rosell-dk/exec-with-fallback/blob/main/tests/LineSplittingTest.php

And a successful CI run on a project that runs those tests:
https://github.com/rosell-dk/exec-with-fallback/actions/runs/1520070091

Javascript demos of the principle
Here are some javascript demos of similar regular expressions (I'm using N and R instead of \n and \r).

Preserve linebreaks demo: https://regexr.com/6ahvl
Remove linebreaks demo: https://regexr.com/6ai0j

PS: There is currently a bug in regexr which causes it to show "Error" when first loaded. Editing the expression makes the error go away

As easy as it seems

$skuList = explode('\\n', $_POST['skuList']);

You just need to pass the exact text "\n" and writing \n directly is being used as an Escape Sequence. So "\\" to pass a simple backward slash and then put "n"

PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.

Try this:

$myString = "Prepare yourself to be caught
You in the hood gettin' shot
We going throw hell of blows
got my whole frame froze";

$myArray = explode(PHP_EOL, $myString);

print_r($myArray);

Here is what worked for me. Tested in PHP 5.6 as well as as PHP 7.0:

    $skuList = str_replace("\\r\\n", "\n", $_POST['skuList']);
    $skuList = str_replace("\\n\\r", "\n", $skuList);

    $skuList = preg_split("/\n/", $skuList);
    print_r($skuList);
Related