开发者

explode error \r\n and \n in windows and linux server

I have used explode function to get text开发者_运维问答area's contain into array based on line. When I run this code in my localhost (WAMPserver 2.1) It work perfectly with this code :

$arr=explode("\r\n",$getdata);

When I upload to my linux server I need to change above code everytime into :

$arr=explode("\n",$getdata);

What will be the permanent solution to me. Which common code will work for me for both server?

Thank you


The constant PHP_EOL contains the platform-dependent linefeed, so you can try this:

$arr = explode(PHP_EOL, $getdata);

But even better is to normalize the text, because you never know what OS your visitors uses. This is one way to normalize to only use \n as linefeed (but also see Alex's answer, since his regex will handle all types of linefeeds):

$getdata = str_replace("\r\n", "\n", $getdata);
$arr = explode("\n", $getdata);


As far as I know the best way to split a string by newlines is preg_split and \R:

preg_split('~\R~', $str);

\R matches any Unicode Newline Sequence, i.e. not only LF, CR, CRLF, but also more exotic ones like VT, FF, NEL, LS and PS.

If that behavior isn't wanted (why?), you could specify the BSR_ANYCRLF option:

preg_split('~(*BSR_ANYCRLF)\R~', $str);

This will match the "classic" newline sequences only.


Well, the best approach would be to normalize your input data to just use \n, like this:

$input = preg_replace('~\r[\n]?~', "\n", $input);

Since:

  • Unix uses \n.
  • Windows uses \r\n.
  • (Old) Mac OS uses \r.

Nonetheless, exploding by \n should get you the best results (if you don't normalize).


The PHP_EOL constant contains the character sequence of the host operating system's newline.

$arr=explode(PHP_EOL,$getdata);


You could use preg_split() which will allow it to work regardless:

$arr = preg_split('/\r?\n/', $getdata);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜