Home > Enterprise >  php regex comma pattern not allowed
php regex comma pattern not allowed

Time:08-05

Hi If there is a comma between the quotes, skip it, otherwise split it from the comma.

(12,'is there , comma escape','system')
(12,'is there comma escape','system')

I want Result

array(
[0]=>array([0]=>12,[1]=>'is there , comma escape',[2]=>'system),
[1]=>array([0]=>12,[1]=>'is there comma escape',[2]=>'system)
);

CodePudding user response:

Here is a preg_match_all() approach. The regex pattern used below attempts to match a CSV term in single quotes first, otherwise it grabs all content up until the next comma. This trick avoids the problem of matching a false flag comma inside single quotes.

$input = "(12,'is there , comma escape','system')
(12,'is there comma escape','system')";
preg_match_all("/\(('.*?'|[^,] ),('.*?'|[^,] ),('.*?'|[^,] )\)/", $input, $matches);
$results = array(array());
for ($i=0; $i < count($matches[1]);   $i) {
    $results[$i][0] = $matches[1][$i];
    $results[$i][1] = $matches[2][$i];
    $results[$i][2] = $matches[3][$i];
}
print_r($results);

This prints:

Array
(
    [0] => Array([0] => 12, [1] => 'is there , comma escape', [2] => 'system')
    [1] => Array([0] => 12, [1] => 'is there comma escape', [2] => 'system')
)
  • Related