Explode PHP string by new line
You might encounter a snippet of code that looks deceptively simple when trying to parse user input. A common pattern involves taking a multi-line text block from a form submission and splitting it into an array of individual items. Consider a scenario where you are handling a bulk SKU entry field:
$skuList = explode('\n\r', $_POST['skuList']);
At first glance, this logic seems sound. You want to separate the string at every newline character. However, there is a subtle but critical error in how the delimiter is defined here that will cause the split to fail completely. In PHP's explode function, the second argument expects a single byte or a sequence of bytes representing the literal separator string. When you pass '\n\r', you are not telling PHP to look for a newline followed by a carriage return; you are telling it to look for a backslash character followed by a lowercase 'n', then a backslash and a lowercase 'r'.
The core issue lies in the distinction between escape sequences within string literals and actual characters. Inside double quotes or single quotes, \n represents a newline character (ASCII 10) and \r represents a carriage return (ASCII 13). However, you cannot wrap these two distinct control characters inside a single-quoted string using that syntax if your intention is to pass the literal characters backslash-n. If you intend to split on the actual newlines present in the input, you must not escape them with a backslash unless you specifically want the literal text \n.
To correctly explode a string by line breaks, you need to pass the actual control characters, not their escaped representations. The correct syntax for splitting on a standard Unix newline is simply "\n". If your input might contain Windows-style line endings (CRLF), which are represented as \r\n in code but appear as a carriage return followed by a newline in the raw byte stream, you have two main strategies depending on the consistency of your data.
If the input strictly uses Unix newlines, the fix is straightforward:
$skuList = explode("\n", $_POST['skuList']);
Here, "\n" is a string containing a single byte with an ASCII value of 10. This tells PHP to break the array wherever that specific byte sequence occurs.
If your application must handle legacy Windows inputs or mixed line endings, relying on a single character delimiter might leave empty strings at the end of the array if the text ends with a newline. A more robust approach for handling both \n and \r\n sequences is to use str_replace to normalize the line endings before exploding, or to use explode with a pattern that accounts for variations. However, explode does not support regular expressions natively; it only splits on literal strings.
To handle mixed environments without complex logic, you can normalize the input first:
$input = str_replace(["\r\n", "\r", "\n"], "\n", $_POST['skuList']);
$skuList = explode("\n", $input);
This ensures that whether the user submitted data from Windows, macOS, or Linux, the resulting array contains clean elements without empty strings caused by trailing line breaks. It is important to trim the input as well if you want to ignore accidental whitespace around the lines:
$skuList = array_map('trim', explode("\n", preg_replace('/\r\n|\r|\n/', "\n", $_POST['skuList'])));
This pipeline normalizes all line endings to \n and then trims each resulting element. The trade-off here is a slight increase in memory usage due to the string manipulation before splitting, but for typical SKU lists, this overhead is negligible compared to the benefit of robust parsing.
When dealing with user input via $_POST, always remember to validate that the input is not empty before attempting to explode it. An empty string passed to explode returns an array containing a single empty string element, which might break downstream logic expecting an empty list. Check for this condition explicitly:
if (!empty($_POST['skuList'])) {
$skuList = array_filter(array_map('trim', explode("\n", preg_replace('/\r\n|\r|\n/', "\n", $_POST['skuList']))));
} else {
$skuList = [];
}
This approach ensures your application handles edge cases gracefully, preventing runtime errors or unexpected data processing issues later in the pipeline.