Determine newline return method in PHP
Question
What would be the best way to detect newline return method in PHP. CR, LF or CR+LF
And if possible convert it to specified type.
Solution
define('NL_NIX', "\n");
define('NL_WIN', "\r\n");
define('NL_MAC', "\r");
function newline_type($string)
{
if (strpos($string, NL_WIN) !== false) {
return NL_WIN;
} elseif(strpos($string, NL_MAC) !== false) {
return NL_MAC;
} elseif(strpos($string, NL_NIX) !== false) {
return NL_NIX;
}
}
Checks what kind of newline is in the string. 0 is returned when no newline is found.
To normalize/standardize all newlines use the following function:
function newline_convert($string, $newline)
{
return str_replace(array(NL_WIN, NL_MAC, NL_NIX), $newline, $string);
}
Hope it helps!
OTHER TIPS
This will test a string for a newline character (CR or LF):
function has_newline($string)
{
return (strpos($string, "\r") !== false || strpos($string, "\n") !== false);
}
(\r
means CR and \n
means LF)
You can use the same thinking to convert them. For example, this function converts all CRs to LFs in a given string:
function replace_returns($string)
{
return str_replace("\r", "\n", $string);
}
The constant PHP_EOL
contains the platform specific newline character.
You can do a $string = nl2br($string) so that your line break is changed to
<br />.
Then you can manipulate the string, e.g. split it up by the first occurance of
<br />
like this:
list($first, $second) = explode('<br />', $string, 2);