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.
You can use a simple regex to solve this:
preg_match('/^(\w*)\s\((\w*)\)$/', $citysearch, $matches);
var_dump($matches);
echo "city: ".$matches[1]."
";
echo "country: ".$matches[2]."
";
Update:
Or without regex:
$citysearch = 'Madrid (Spain)';
$pos = strpos($citysearch, ' (');
$city = substr($citysearch, 0, $pos);
$country = substr($citysearch, $pos + 2, -1);
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
using explode
$citysearch = "Madrid (Spain)";
$ar =explode("(",$citysearch,2);
$ar[1]=rtrim($ar[1],")");
$city = $ar[0];
$country = $ar[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