4

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

Aryan G
  • 1,281
  • 10
  • 30
  • 51

5 Answers5

7

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);
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
  • 1
    Some operating systems use \r as a newline though, you need to deal with that too. – GordonM Apr 24 '11 at 08:54
  • GordonM, you are correct. The ten year old Mac OS 9 uses \r (as well as some systems from the 80's), but I don't think anyone is running a web server on that old software. – Emil Vikström Apr 24 '11 at 09:00
  • 1
    True enough, but it never hurts to keep your bases covered :) – GordonM Apr 24 '11 at 09:01
  • 1
    The `PHP_EOL` constant is relative to the server environment, the input data might have other origins. – Alix Axel Apr 24 '11 at 09:03
  • Alix, true, that's why it's better to normalize the input. Your regex may be the best solution (I'm clarifying my answer as well, but not stealing your fame :-)). – Emil Vikström Apr 24 '11 at 09:05
6

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.

NikiC
  • 100,734
  • 37
  • 191
  • 225
1

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

Alix Axel
  • 151,645
  • 95
  • 393
  • 500
0

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

$arr=explode(PHP_EOL,$getdata);
GordonM
  • 31,179
  • 15
  • 87
  • 129
0

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

$arr = preg_split('/\r?\n/', $getdata);
James C
  • 14,047
  • 1
  • 34
  • 43