dounai9592 2016-05-11 16:07 采纳率: 100%
浏览 95
已采纳

在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.

  • 写回答

4条回答 默认 最新

  • dongshaidu2456 2016-05-11 16:10
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容