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

时间:2016-05-11 16:07:07

标签: php

我有一个包含以下格式的字符串:city (Country)我希望将 city country 分开并将值存储在2个不同的变量中

我尝试了以下内容,它正在努力存储城市而不是国家。

<?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;;

?>

任何帮助都将受到高度赞赏。

4 个答案:

答案 0 :(得分:3)

您可以使用简单的正则表达式来解决此问题:

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

<强>更新
或者没有正则表达式:

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

答案 1 :(得分:1)

在php中使用explode

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

使用preg_split

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

输出:

Madrid Spain

答案 2 :(得分:0)

我认为你应该选择这个简单的例子:

只需使用explode函数展开字符串,然后将该城市存储在$city变量中,并将该国家/地区存储在$country变量中。

在爆炸字符串后,您将获得一个数组,其中索引0中的值为Madrid,索引1为(Spain)。因此,使用$div[0]很容易获得城市,但对于国家/地区,您需要使用名为trim的空间函数来清除()。并使用$div[1]来获取国家。

示例:

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

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

答案 3 :(得分:0)

使用爆炸

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