"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to reliably split strings into lines by different newlines in PHP?

How to reliably split strings into lines by different newlines in PHP?

Posted on 2025-05-02
Browse:161

How Can I Reliably Split Strings into Lines in PHP, Handling Various Newline Characters?

Exploding PHP Strings by Newline

When working with text in PHP, you may need to separate a string into lines. Traditionally, this has been done using the explode function with a newline character as the delimiter. However, this approach can lead to unexpected results if the input string contains variations in newline characters.

Addressing the Specific Issue

The provided code:

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

is meant to split the skuList input on both Windows-style (\r\n) and UNIX-style (\n) newlines. However, this approach is not system-independent, and may fail on systems that use different newline characters.

Best Practices

To ensure system independence, consider using the PHP_EOL constant:

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

PHP_EOL represents the current system's newline character, ensuring consistent behavior. Alternatively, you can use preg_split for finer control:

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

This regex matches all possible newline variations, ensuring comprehensive splitting.

Considerations

Using system-independent constants makes your code portable, but it's important to note that issues may arise when moving data between systems with different newline conventions. To avoid this, parse data thoroughly before storage and remove any system-dependent elements.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3