comma-separated string to array

前端 未结 3 692
温柔的废话
温柔的废话 2020-12-02 01:00

I\'m looking for the simplest way to take a single variable such as:

$variable = \'left,middle,right\';

and write it to an array();

相关标签:
3条回答
  • 2020-12-02 01:12
    $array = explode(',', $variable);
    
    0 讨论(0)
  • 2020-12-02 01:13

    In case you string gets a little bit more complex (i.e. elements can be in quotes and both the delimiter and the quoting character can appear within an element) you might also be interested in fgetcsv() and str_getcsv()

    $variable = '"left,right","middle", "up,down"';
    $row = str_getcsv($variable);
    var_dump($row);
    

    prints

    array(3) {
      [0]=>
      string(10) "left,right"
      [1]=>
      string(6) "middle"
      [2]=>
      string(7) "up,down"
    }
    
    0 讨论(0)
  • 2020-12-02 01:24

    you can also use preg_split()

    $variable = 'left  ,  middle,   right';
    print_r ( preg_split("/\s*,\s*/",$variable));
    
    0 讨论(0)
提交回复
热议问题