Capture value within the string

Asked

Viewed 51 times

1

Well I have a variable that receives a string, with the name of the city and can happen to have the neighborhood within parentheses. I need you to separate that into two variables.

Example 1:

$cidade = "BOA ESPERANÇA";

Return I need.

$nome_cidade = "BOA ESPERANÇA";
$bairro = null;

Example 2:

$cidade = "BOA ESPERANÇA (CENTRO)";

Return I need.

$nome_cidade = "BOA ESPERANÇA";
$bairro = "CENTRO";

How can I do that?

  • Regular expression is a solution.

  • 2

    I believe that more information is missing in the question Hugo, what are the possible variations of the name of the city? will always be the name followed by the center between parentheses?

  • And if only open parenthesis, but not close it, should be considered as neighborhood, as in "BOA ESPERANÇA (CENTRO"?

  • First of all you need to find the regular pattern in all occurrences, because any solution that appears will only serve for the examples presented, which apparently does not represent the problem as a whole.

  • @RFL the neighborhood will always come within parentheses, however it may occur not to come the neighborhood soon will not have the parentheses

2 answers

4


Do it this way:

<?php
  $cidade = "CIDADE (BAIRRO)";
  $options = explode("(", $cidade);

  if(isset($options[1])) $bairro = str_replace(")","",$options[1]);
  else $bairro = null;
  $nome_cidade = str_replace(" ","",$options[0]);

?>

3

/([^\(]+)\(?([^\)]+)?\)?/
  1. ([^\(]+), creates a capture group for any character other than (;
  2. \(?, sets the literal character ( as an optional;
  3. ([^\)]+), creates a capture group for any character other than );
  4. \)?, sets the literal character ) as an optional;

Thus:

function get_cidade_bairro($nome)
{
    if (preg_match('/([^\(]+)\(?([^\)]+)?\)?/', $nome, $matches)) {
        return [
            'cidade' => $matches[1],
            'bairro' => $matches[2] ?? null
        ];
    }

    return null;
}


$tests = [
    "BOA ESPERANÇA",
    "BOA ESPERANÇA (CENTRO)"
];

foreach ($tests as $test) {
    var_export( get_cidade_bairro($test) );
}

The exit is:

array (
  'cidade' => 'BOA ESPERANÇA',
  'bairro' => NULL,
)

array (
  'cidade' => 'BOA ESPERANÇA ',
  'bairro' => 'CENTRO',
) 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.