You can use this pattern with preg_split
$pattern = '~(?=\[[^]]*])|]\K(?=[^[])~';
or more simple:
$pattern = '~(?=\[)|]\K(?=[^[])~';
or:
$pattern = '~(?=\[)|(?<=])~';
Question
Using PHP, How can I split the following string "Random words [Ab]another few words here [Bx]and yet a [Sq4]few more" into the following array:
array[0] = 'Random words '
array[1] = '[Ab]'
array[2] = 'another few words here '
array[3] = '[Bx]'
array[4] = 'and yet a '
array[5] = '[Sq4]'
array[6] = 'few more'
where the String [xxx] acts as the delimiter and there can be 1-4 alpha numeric characters inbetween the braces?
Also how would I do something similar where I create two arrays:
arrayA[0] = 'Random words '
arrayA[1] = 'another few words here '
arrayA[2] = 'and yet a '
arrayA[3] = 'few more'
arrayB[0] = '[Ab]'
arrayB[1] = '[Bx]'
arrayB[2] = '[Sq4]'
Any help here would be greatly appreciated!
Solution
You can use this pattern with preg_split
$pattern = '~(?=\[[^]]*])|]\K(?=[^[])~';
or more simple:
$pattern = '~(?=\[)|]\K(?=[^[])~';
or:
$pattern = '~(?=\[)|(?<=])~';