【问题标题】:PHP: convert string to arrayPHP:将字符串转换为数组
【发布时间】:2015-04-02 10:48:52
【问题描述】:

我有这个字符串

[1: boy, 2: girl]

我希望它转换为数组

1=>boy
2=>girl

【问题讨论】:

  • 你试过了吗?
  • 我试过explode(),但是太复杂了
  • 如果你用谷歌搜索“php string to array”,你会从字面上找到数百个问题的答案。

标签: php arrays string


【解决方案1】:

您好,您可以使用 explode 来获得所需的输出

$tp = '[1: boy, 2: girl]';
$tp = trim($tp,'[]');
$new = array();
foreach(explode(',',$tp) as $each_elem){
    $temp = explode(':',$each_elem);
    $new[trim($temp[0])] = $temp[1];
}

【讨论】:

    【解决方案2】:

    试试这个:

    $str = "[5: boy, 8: girl]";
    $exps = preg_split('/\W/',$str, 0,PREG_SPLIT_NO_EMPTY);
    $size = count($exps);
    for($i=0; $i<$size; $i++)
        $array[$exps[$i]] = $exps[++$i];
    

    输出:

    5=>boy
    8=>girl
    

    【讨论】:

      【解决方案3】:

      简单的正则表达式解决方案:

      preg_match_all('/(\d+): ([^,\]]+)/', $string, $matches);
      $array = array_combine($matches[1], $matches[2]);
      

      【讨论】:

        猜你喜欢
        • 2018-01-29
        • 2013-08-12
        • 2021-12-27
        • 2010-10-15
        • 1970-01-01
        • 2013-05-12
        • 2013-04-27
        • 2016-04-28
        相关资源
        最近更新 更多