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

I used the break function to get textarea into a string based array. When I run this code in my localhost (WAMPserver 2.1), it works fine with this code:

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

When I boot to my Linux server, I need to change the code above each time:

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

What will be the permanent solution for me. What common code will work for me for both servers?

thanks

+4
source share
5 answers

Permanent PHP_EOL contains a platform-specific string, so you can try the following:

 $arr = explode(PHP_EOL, $getdata); 

But itโ€™s even better to normalize the text, because you never know which OS your visitors are using. This is one way to normalize using only \ n as a newline (but also see Alex's answer, as its regular expression will process all types of strings):

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

As far as I know, the best way to split a line into new lines is preg_split and \R :

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

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

If this behavior is not required (why?), You can specify the BSR_ANYCRLF option:

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

This will only match the "classic" newline sequences.

+6
source

Well, the best approach would be to normalize your input to just use \n , for example:

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

WITH

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

However, sprawling \n should give you the best results (if you don't normalize).

+1
source

The PHP_EOL constant contains a sequence of newline characters for the host operating system.

 $arr=explode(PHP_EOL,$getdata); 
0
source

You can use preg_split() , which will allow it to work independently:

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

All Articles