With PHP, how can I split a string into an array where the delimiters are a variable string enclosed with braces like '[Ab]'

StackOverflow https://stackoverflow.com/questions/17460767

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!

Was it helpful?

Solution

You can use this pattern with preg_split

$pattern = '~(?=\[[^]]*])|]\K(?=[^[])~';

or more simple:

$pattern = '~(?=\[)|]\K(?=[^[])~';

or:

$pattern = '~(?=\[)|(?<=])~';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top