Skip to content
Advertisement

Split a string at comma character but ignore if said character is nested inside parentheses

I’m currently working as a php dev, and now has an assignment with some old php legacy code that’s intended to filter certain car details before adding it into the DB. What I’m currently stuck on is how I’m supposed to skip splitting the models inside of the parenthesis

Example:

"v70, 790, v50 (v40, v44), v22"

Expected output:

[ "v70", "790", "v50 (v40, v44)", "v22" ]

So that the , inside of the parentheses is disregarded by the split. Any help and pointers is greatly appreciated!

Advertisement

Answer

You can use preg_split() method for this (documentation). You can use this to split the string based on a regex pattern for comma separated values but ignored if these are between parentheses.

This code works for your example:

<?php

$string = 'v70, 790, v50 (v40, v44), v22';
$pattern = '/,(?![^(]*)) /';
$splitString = preg_split($pattern, $string);

Output of $splitString looks like:

array (size=4)
  0 => string 'v70' (length=3)
  1 => string '790' (length=3)
  2 => string 'v50 (v40, v44)' (length=14)
  3 => string 'v22' (length=3)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement