4

I am trying to break a string into an array using the explode function.

I want it break the string using the line breaks found inside the string.

I looked it up and I tried all the ways but I can't get it to work.

Here is what I have so far:

$r = explode("\r\n" , $roster[0]);

But when I var_dump the variable, I get the following:

array (size=1)
  0 => string '\r\n                         ( G  A  Sh Hi Ga Ta PIM, +\/-  Icetime Rating)\r\nR Danny Kristo            1  0  2  0  0  0    0    1    7.00    7\r\nR Brian Gionta            1  1  5  1  1  0    0    0   19.20    8\r\nR Steve Quailer...

Any ideas why?

raina77ow
  • 103,633
  • 15
  • 192
  • 229
Ara Sivaneswaran
  • 365
  • 1
  • 10
  • 25

3 Answers3

15

You can try to split the string with a regular expression. There is a class for newline characters:

$r = preg_split('/\R/', $string);

Edit: Add missing delimiters to the regex and argument to function.

Lucas Kahlert
  • 1,207
  • 9
  • 16
  • I tried it and I got this: preg_split(): Delimiter must not be alphanumeric or backslash – Ara Sivaneswaran Jun 08 '13 at 22:59
  • I've corrected the regular expression. You should know, that only "true" newlines are identified by this expression. As raina77ow posted, the '\r\n' in your string are no newline characters but four individual characters. Therefore the regular expression will not match. – Lucas Kahlert Jun 12 '13 at 22:37
6

The problem is that \r\n in the original text are NOT end of line symbols - it's just literally 'backslash-r-backslash-n' sequence. Hence you need to take this into account:

$r = explode('\r\n', $roster[0]);

... i.e., use single quotes to delimit the string.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • Thanks, it said everywhere that I should put double quotes and not single... THanks! – Ara Sivaneswaran Jun 08 '13 at 23:00
  • 1
    better use `PHP_EOL` for platform independent solution. – Fr0zenFyr Aug 16 '16 at 07:59
  • 1
    @Fr0zenFyr You miss the point, the title is misleading here. The OP has the string with slashes followed by `r` and `n`, not the EOL symbols. Had it been the way, @LucasKahlert answer would fit the best, as `\R` metacharacter covers all the bases. – raina77ow Aug 16 '16 at 12:36
6

You can use system dependent EOL

 $r = explode(PHP_EOL, $roster[0]);