Home > Backend Development > PHP Tutorial > How to Reliably Explode a PHP String by New Line Characters?

How to Reliably Explode a PHP String by New Line Characters?

Linda Hamilton
Release: 2024-12-02 12:15:10
Original
681 people have browsed it

How to Reliably Explode a PHP String by New Line Characters?

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']);
Copy after login

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']);
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template