Samuel del Rio Samuel del Rio - 5 months ago 7x
PHP Question

Split a string into 2 variables in PHP

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.


$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);
echo "city: ".$matches[1]."\n";
echo "country: ".$matches[2]."\n";

Or without regex:

$citysearch = 'Madrid (Spain)';
$pos = strpos($citysearch, ' (');
$city = substr($citysearch, 0, $pos);
$country = substr($citysearch, $pos + 2, -1);