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

隐身守侯 提交于 2019-11-26 08:57:11

问题


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 large number is 10,000\';

$linearray = explode(\",\",$line);
$linemysql = implode(\"\',\'\",$linearray);

Returns $linemysql as:

\'TRUE\',\'59\',\'A large number is 10\',\'000\'

How can I go about accomplishing this, with the explode ignoring the commas inside the quote marks?


回答1:


Since you are using comma seperated values, you can use str_getcsv.

str_getcsv($line, ",", "'");

Will return:

Array
(
    [0] => TRUE
    [1] => 59
    [2] => A large number is 10,000
)



回答2:


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.




回答3:


You can explode on commas that are immediately followed by a single quote with preg_split() using positive lookahead. This will preserve your single quotes in the output array.

Code: (Demo)

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

Output:

array (
  0 => '\'TRUE\'',
  1 => '\'59\'',
  2 => '\'A large number is 10,000\'',
)

*fyi, the slashes in the result array are just the product of escaping done by var_export().

print_r() shows this (because it doesn't single-quote wrap its values):

Array
(
    [0] => 'TRUE'
    [1] => '59'
    [2] => 'A large number is 10,000'
)


来源:https://stackoverflow.com/questions/5132533/php-how-can-i-explode-a-string-by-commas-but-not-wheres-the-commas-are-within

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!