Explode PHP String by New Line
In PHP, the explode() function is used to split a string into an array based on a specified delimiter. However, when dealing with strings containing new line characters, using the simple "n" delimiter may not always work as expected.
Your code $skuList = explode('nr', $_POST['skuList']); is not working because it uses the "nr" delimiter, which represents both the Windows and Mac new line characters. However, on systems like Linux or Unix, only "n" is used.
Best Practice:
The best practice for exploding strings by new lines is to use the PHP constant PHP_EOL. This constant represents the current system's End Of Line character, ensuring the code is system-independent.
$skuList = explode(PHP_EOL, $_POST['skuList']);
Warning:
While using PHP_EOL promotes system independence, caution should be exercised when moving data between systems. The constant's value may differ between systems, potentially resulting in data inaccuracies. Therefore, it's advisable to parse data thoroughly before storing it to remove any system-dependent elements.
UPDATE:
However, in this specific case, as pointed out by @Andreas, this solution may not be suitable because the new line characters in $_POST['skuList'] are from the browser, not the server. Therefore, a more appropriate solution is recommended by @Alin_Purcaru:
$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);
This regular expression splits the string based on any of the common new line character sequences used by different operating systems.
The above is the detailed content of How to Reliably Explode a PHP String by New Line Characters?. For more information, please follow other related articles on the PHP Chinese website!