12

I have a string that has different values on each line:

$matches="value1
value2
value3
value4
value5
";

I want to explode the whole string in to an array consisting of the values separeted. I know how to explode a space separated string, like explode(' ', $matches). But how do i use the explode function on this type of string?

I tried this:

$matches=explode('\n',$matches);
print_r($matches);

But the result is like:

Array
(
    [0] => hello
hello
hello
hello
hello
hello
hello

)
Sujit Agarwal
  • 12,348
  • 11
  • 48
  • 79
  • 1
    Which OS you are using? Different OS' have different new line characters: http://en.wikipedia.org/wiki/Newline – Felix Kling May 28 '11 at 16:35

2 Answers2

34

You need to change '\n' to "\n".

From PHP.net:

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

\n linefeed (LF or 0x0A (10) in ASCII)
More...

6

Read manual

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

So use "\n" instead of '\n'

Also, instead of \n you can use PHP_EOL constant.
In the Windows "\r\n" can be used as end of line, for this case you can make double replacement:
$matches=explode("\n", str_replace("\r","\n",$matches));

OZ_
  • 12,492
  • 7
  • 50
  • 68