[nycphp-talk] What does this code do?
dcech at phpwerx.net
Mon Mar 3 14:48:21 EST 2008
Steve Manes wrote:
> -- rada -- wrote:
>> supposedly converts Windows CRLF to Unix LF:
>> $str =~ s/\r\n/\n/g;
> Perl sed function.
> There's no need to use a regex function unless you have a regex pattern
> to match. If you just need to remove the carriage returns, this will be
> two or three times faster:
> $str = str_replace("\r", "", $str);
While this is indeed faster than using preg, it suffers from a slightly
different version of the same bug in the original version. On Mac, a
newline is \r, so this will remove all newlines from a mac-formatted
string...not what you want. The original version is only marginally
better in that it leaves the mac newlines unconverted.
A simple and efficient way to convert both windows and mac newlines to
the unix style is:
$str = str_replace(array("\r\n","\r"),"\n",$str);
This will first replace all windows newline sequences with the unix
version, then any mac-style carriage returns.
More information about the talk