Home >Backend Development >PHP Tutorial >How Can I Properly Explode a PHP String by Newline Characters?
Explode PHP String by New Line
Question:
When attempting to explode a PHP string by newline characters using the code below, the operation fails:
$skuList = explode('\n\r', $_POST['skuList']);
Solution:
The correct approach to explode a PHP string by newline is to use the PHP constant PHP_EOL, which represents the current system's end of line (EOL) character.
$skuList = explode(PHP_EOL, $_POST['skuList']);
Additional Considerations:
Expanded Solution:
For cases where the origin of the newline characters is unknown or may vary, a more comprehensive solution is recommended:
$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);
This regular expression pattern matches all common newline characters and ensures that the string is exploded correctly regardless of the operating system's EOL conventions.
The above is the detailed content of How Can I Properly Explode a PHP String by Newline Characters?. For more information, please follow other related articles on the PHP Chinese website!