0

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!

dnpage
  • 95
  • 1
  • 6

1 Answers1

1

You can use this pattern with preg_split

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

or more simple:

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

or:

$pattern = '~(?=\[)|(?<=])~';
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • I tried that and ended up with: Array ( [0] => Random words [1] => [Ab]another few words here [2] => [Bx]and yet a [3] => [Sq4]few more ) – dnpage Jul 04 '13 at 02:07
  • @dnpage: retry with the new pattern – Casimir et Hippolyte Jul 04 '13 at 02:08
  • @Casimir_et_Hippolyte Nice! Array ( [0] => Random words [1] => [Ab] [2] => another few words here [3] => [Bx] [4] => and yet a [5] => [Sq4] [6] => few more ) and from there I can loop through the array and pick out the ones that begin with '[' to make my 2 arrays. I really do need to study regular expressions and see how you built that pattern. Thanks for your help! – dnpage Jul 04 '13 at 02:11