在PHP中将字符串拆分为2个变量

在PHP中将字符串拆分为2个变量

问题描述:

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.

我有一个字符串,格式如下: city(Country) code>我想要 将 city em>和 country em>分开并将值存储在2个不同的变量中。 p>

我尝试了以下操作并且正在努力 存储城市而不是国家。 p>

 &lt;?php 
 
 $ citysearch =“Madrid(Spain)”; 
echo $ citysearch; 
 
  $ citylen = strlen($ citysearch); 
for($ i = 0; $ i&lt; = $ citylen; $ i ++)
 {
 $ char = substr($ citysearch,$ i,1); 
 if  ($ char&lt;&gt;“(”)
 {
 echo $ city。“&lt; br&gt;”; 
 $ city = $ city。$ char; 
 if($ char ==“”)\  n {
 break; 
} 
} 
 if($ char&lt;&gt;“)”)
 {
 echo $ country。  “&LT峰; br&gt;” 中;  
 $ country = $ country。$ char; 
 if($ char ==“)”)
 {
 break; 
} 
} 
} 
 
echo“这是城市:”  。$ city; 
echo“这是国家:”。  $ country ;; 
 
?&gt; 
  code>  pre> 
 
 

我们非常感谢任何帮助。 p> div>

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