How to explode a multi-line string?

I have a line that has different meanings in each line:

$matches="value1 value2 value3 value4 value5 "; 

I want to split the entire string into an array consisting of divided values. I know how to explode a string separated by a space, like explode(' ', $matches) . But how can I use the diversity function for this type of string?

I tried this:

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

But the result is this:

 Array ( [0] => hello hello hello hello hello hello hello ) 
+9
source share
2 answers

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

From PHP.net :

If the string is enclosed in double quotation marks ("), PHP interprets more escape sequences for special characters:

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

+28
source

Read manual

Note. Unlike double quotes and heredoc syntaxes, variables and escape sequences for special characters will not expand when they occur in single quotes.

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

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

+5
source

All Articles