0

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"
)
2
  • You may want to indicate and tag what language you're trying to do this in. Commented Jul 27, 2017 at 3:38
  • 1
    php.net/manual/en/function.preg-split.php Commented Jul 27, 2017 at 3:44

2 Answers 2

2

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.

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

Comments

1

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)

\n is 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.

2 Comments

And now, how do i cite these strings? Ex: echo xx[2]; ->> "Águia Branca"
@w4g I modified my answer to add the $result variable. To cite a string, just use $result[2] for example.

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.