PHP: How can I explode a string by commas, but not wheres the commas are within quotes?

前端 未结 3 1473
情话喂你
情话喂你 2020-11-28 11:44

I need to explode my string input into an array at the commas. However the string contains commas inside quotes.

Input:

$line = \'TRUE\',\'59\',\'A l         


        
3条回答
  •  清酒与你
    2020-11-28 12:22

    It seems you do not want to split your string by commas, but by the succession of quote+comma+quote ?

    If so, the preg_split function might help, here.


    For example, using this portion of code :

    $line = "'TRUE','59','A large number is 10,000'";
    $parts = preg_split("/','/", $line);
    var_dump($parts);
    

    I get the following output :

    array
      0 => string ''TRUE' (length=5)
      1 => string '59' (length=2)
      2 => string 'A large number is 10,000'' (length=25)
    

    Starting with that, it's now a matter of removing the first and last quotes of the $line string, before calling preg_split -- as those are delimiters, and don't match the splitting pattern.

提交回复
热议问题