NYCPHP Meetup

NYPHP.org

[nycphp-talk] What does this code do?

Dan Cech dcech at phpwerx.net
Mon Mar 3 14:51:42 EST 2008


Dan Cech wrote:
> 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.

Before the flames begin, let me assure the Mac users out there that I 
meant to say *old* Mac newlines are simply \r.  OSX uses unix-style \n 
newlines.

Dan



More information about the talk mailing list