My string is this:
$brazil = "Afonso Cláudio
Água Doce do Norte
Águia Branca";
I want to split this string into an array like this:
Brazil (
[0] => "Afonso Cláudio"
[1] => "Água Doce do Norte"
[2] => "Águia Branca"
)
My string is this:
$brazil = "Afonso Cláudio
Água Doce do Norte
Águia Branca";
I want to split this string into an array like this:
Brazil (
[0] => "Afonso Cláudio"
[1] => "Água Doce do Norte"
[2] => "Águia Branca"
)
As tempting as it may be to explode() on a newline character, this solution is of limited usefulness because it depends on what character(s) your platform uses. A line may terminate with one or a combination of the following characters: a form feed ("\f"), a carriage return ("\r"), a newline ("\n"). The following code splits the string value contained in $brazil accordingly, as follows:
<?php
$brazil = "Afonso Cláudio
Água Doce do Norte
Águia Branca";
$arr = preg_split("/[\f\r\n]+/",$brazil );
var_dump($arr);
See live code
You may attain the same result using this regex: "/\R/"; see here.
See preg_split() for more info.
Returning to using explode(), instead of hardcoding the newline character, use the built-in constant PHP_EOL, as follows:
<?php
$brazil = "Afonso Cláudio
Água Doce do Norte
Águia Branca";
$arr = explode(PHP_EOL,$brazil );
var_dump($arr);
See demo.
PHP_EOL is a built-in constant designed to match whatever character(s) your OS uses to terminate lines.
Useful resources: Escape Sequences, PHP_EOL, Why You Should use PHP_EOL.
To do that, you need to simply divide your string in multiple lines. To do that, you need to use the explode() method that divides a string by a certain character.
In your case, you want to divide the string by new lines. To do that, you need this:
$result = explode("\n", $brazil)
\nis an escape character representing a new line.
The method will return this array:
array(3) {
[0]=>
string(16) "Afonso Cláudio
"
[1]=>
string(20) "Água Doce do Norte
"
[2]=>
string(13) "Águia Branca"
}
Note: The only remaining problem is that you still have the newline character at the end of every string. You can solve that be removing the last character from each string in the array. See this question for more information on how to do that.