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

半世苍凉 提交于 2019-11-30 22:50:32

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