duanhe1903
2013-11-11 00:04
浏览 441
已采纳

PHP将带有方括号的逗号分隔字符串转换为数组

My string looks like:

[10,20,30]

I want to convert it to an array.

I've tried:

$myArray=explode(",",$myString);
print_r($myArray);

But this is returning:

Array ( [0] => [10 [1] => 20 [2] => 30] )

I need to get rid of the opening/closing brackets.

Can someone help?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanjiao6730 2013-11-11 00:05
    已采纳

    An array of numbers in that particular format is valid JSON, so you can use PHP’s built-in function:

    $myArray = json_decode($myString);
    
    打赏 评论
  • doujun5009 2018-11-28 06:18

    I think you can remove the square brackets first with str_replace function. Then you can simply do the rest. This will work I think.

    $inputString = "[10,20,30]";
    $processString = str_replace(array('[',']') ,'' , $inputString);
    $outputArray = explode(',' , $processString);
    var_dump($outputArray);
    
    //output:
    //array(3) { [0]=> string(2) "10" [1]=> string(2) "20" [2]=> string(2) "30" }
    
    打赏 评论

相关推荐 更多相似问题