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 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3