I want to explode a variable in a little different way

前端 未结 5 1936
遇见更好的自我
遇见更好的自我 2021-02-04 01:30

I have this variable.

$var = \"A,B,C,D,\'1,2,3,4,5,6\',E,F\";

I want to explode it so that I get the following array.

array(
[0         


        
5条回答
  •  孤城傲影
    2021-02-04 02:07

    There is an existing function that can parse your comma-separated string. The function is str_getcsv

    It's signature is like so:

    array str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )
    

    Your only change would be to change the 3rd variable, the enclosure, to single quotes rather than the default double quotes.

    Here is a sample.

    $var = "A,B,C,D,'1,2,3,4,5,6',E,F";
    $array = str_getcsv($var,',',"'");
    

    If you var_dump the array, you'll get the format you wanted:

    array(7) {
      [0]=>
      string(1) "A"
      [1]=>
      string(1) "B"
      [2]=>
      string(1) "C"
      [3]=>
      string(1) "D"
      [4]=>
      string(11) "1,2,3,4,5,6"
      [5]=>
      string(1) "E"
      [6]=>
      string(1) "F"
    }
    

提交回复
热议问题