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

醉酒当歌 提交于 2019-12-03 21:21:59

问题


I have used explode function to get textarea'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


回答1:


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);



回答2:


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.




回答3:


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).




回答4:


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

$arr=explode(PHP_EOL,$getdata);



回答5:


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

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


来源:https://stackoverflow.com/questions/5769589/explode-error-r-n-and-n-in-windows-and-linux-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!