I want to explode a variable in a little different way

前端 未结 5 1938
遇见更好的自我
遇见更好的自我 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 01:54

    Although preg_split along with array_map is working very good, see below an example using explode and trim

    $var = "A,B,C,D,'1,2,3,4,5,6',E,F";
    
    $a = explode("'",$var);
    
    //print_r($a);
    /*
    outputs
    Array
    (
        [0] => A,B,C,D,
        [1] => 1,2,3,4,5,6
        [2] => ,E,F
    )
    */
    $firstPart = explode(',',trim($a[0],',')); //take out the trailing comma
    /*
    print_r($firstPart);
    outputs
    Array
    (
        [0] => A
        [1] => B
        [2] => C
        [3] => D
    )
    */
    $secondPart = array($a[1]);
    
    $thirdPart = explode(',',trim($a[2],',')); //tale out the leading comma
    /*
    print_r($thirdPart);
    Array
    (
        [0] => E
        [1] => F
    )
    */
    
    $fullArray = array_merge($firstPart,$secondPart,$thirdPart);
    print_r($fullArray);
    /*
    ouputs
    Array
    (
        [0] => A
        [1] => B
        [2] => C
        [3] => D
        [4] => 1,2,3,4,5,6
        [5] => E
        [6] => F
    )
    */
    

提交回复
热议问题