Splitting a PHP String by Newline Characters
When dealing with multiline inputs, it's common to need to split a string into an array of individual lines. The PHP explode function can be used for this purpose, but it requires the correct delimiter to accurately divide the string.
The initial attempt, using explode('nr', $_POST['skuList']), fails because it assumes the newline character is a Windows-style carriage return followed by a line feed (rn). However, depending on the operating system and input source, the newline character may vary.
Best Practice: Using PHP_EOL
To address this system dependency, it's recommended to use the PHP constant PHP_EOL. This constant represents the end-of-line character for the current system, ensuring that the string is split consistently regardless of the environment.
$skuList = explode(PHP_EOL, $_POST['skuList']);
Caution: System Dependency in Data
While using PHP_EOL makes code system independent, it's important to be aware of potential issues when moving data between systems. The new system's PHP_EOL constant may differ, potentially breaking stored data. To avoid this, fully parse and clean data before storage to remove system-dependent components.
Browser-Specific Newline Characters
In the context of this specific use case, it's worth noting that the string is coming from the browser. Browsers use different newline characters depending on the operating system. To handle all possibilities, the following regular expression can be used:
$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);
This expression matches any of the possible newline characters, ensuring that the string is correctly split regardless of the source.
The above is the detailed content of How Can I Reliably Split a Multiline String in PHP?. For more information, please follow other related articles on the PHP Chinese website!