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

)
1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.