I want to split like this:
Before:
TEST_A, TEST_B, TEST_C (with A, B, C), TEST_D
After:
TEST_A
TEST_B
TEST_C (with A, B, C)
TEST_D
How can I split it?
I want to split like this:
TEST_A, TEST_B, TEST_C (with A, B, C), TEST_D
TEST_A
TEST_B
TEST_C (with A, B, C)
TEST_D
How can I split it?
Regex isn’t going to help this time, so you will have to iterate through the characters.
Fact is, regular expressions aren’t very context-aware. For that reason, you can’t use regular expression to parse HTML. This is why we’re better off iterating through the string ourselves.
function magic_split($str) {
$sets = array(''); // Sets of strings
$set_index = 0; // Remember what index we’re writing to
$brackets_depth = 0; // Keep track if we’re in brackets (or not)
// Iterate through entire string
for($i = 0; $i < strlen($str); $i++) {
// Skip commas if we’re not in brackets
if($brackets_depth < 1 && $str[$i] === ',') continue;
// Add character to current list
$sets[$set_index] .= $str[$i];
// Store brackets depth
if($str[$i] === '(') $brackets_depth++;
if($str[$i] === ')') $brackets_depth--;
if(
$i < strlen($str) - 1 && // Is a next char available?
$str[$i+1] === ',' && // Is it a comma?
$brackets_depth === 0 // Are we not in brackets?
) $sets[++$set_index] = ''; // Add new set
}
return $sets;
}
$input = 'TEST_A, TEST_B, TEST_C (with A, B, C), TEST_D';
$split = magic_split($input);