1

I have a string with the following format: city (Country) and I would like to separate the city and the country and store the values in 2 different variables.

I tried the following and it is working to store the city but not for the country.

<?php

$citysearch = "Madrid (Spain)";
echo $citysearch;

$citylen = strlen( $citysearch );
for( $i = 0; $i <= $citylen; $i++ )
{
  $char = substr( $citysearch, $i, 1 );
  if ($char <> "(")
  {
    echo $city. "<br>"; 
    $city = $city .$char;
    if ($char == " ")
    {
      break;
    } 
  }
  if ($char <> ")")
  {
    echo $country. "<br>"; 
    $country = $country .$char;
    if ($char == ")")
    {
      break;
    } 
  }
}

echo "This is the city:" .$city;
echo "This is the country:" . $country;;

?>

Any help would be highly appreciated.

2
  • 1
    If it's always in the same format, have a look at preg_match. Commented May 11, 2016 at 16:09
  • @SamueldelRio, your answer is ready. Check Commented May 11, 2016 at 16:27

4 Answers 4

3

You can use a simple regex to solve this:

preg_match('/^(\w*)\s\((\w*)\)$/', $citysearch, $matches);
var_dump($matches);
echo "city: ".$matches[1]."\n";
echo "country: ".$matches[2]."\n";

Update:
Or without regex:

$citysearch = 'Madrid (Spain)';
$pos = strpos($citysearch, ' (');
$city = substr($citysearch, 0, $pos);
$country = substr($citysearch, $pos + 2, -1);
Sign up to request clarification or add additional context in comments.

Comments

1

Using explode in php :

<?php
$citysearch = "Madrid (Spain)";
$myArray = explode('(', $citysearch);
print($myArray[0]);
print(rtrim($myArray[1], ")"));
?>

Using preg_split:

<?php
$citysearch = "Madrid (Spain)";
$iparr = preg_split ("/\(/", rtrim($citysearch, ")"));
print($iparr[0]);
print($iparr[1]);
?>

Output:

Madrid Spain

Comments

0

I think you should go with this simple example:

Just explode the string with explode function, then store the city in the $city variable and store the country in $country variable.

After exploding the string you will get an array, where in index 0 is the value Madrid and index 1 is (Spain). So its easy to get the city using $div[0], but for country you need to use a spacial function called trim for clearing the (). and use $div[1] to get the country.

Example:

$citysearch = "Madrid (Spain)";
$div = explode(" ", $citysearch);

echo $city = $div[0]; //Madrid
echo $country = trim($div[1], "()"); //Spain

Comments

0

using explode

$citysearch = "Madrid (Spain)";
$ar =explode("(",$citysearch,2);
$ar[1]=rtrim($ar[1],")");
$city = $ar[0];
$country = $ar[1];

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.