0

使用 PHP,我如何将以下字符串“随机单词 [Ab]another few words here [Bx]and yet a [Sq4]few more”拆分为以下数组:

 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'

其中字符串 [xxx] 充当分隔符,大括号之间可以有 1-4 个字母数字字符?

另外,在创建两个数组的情况下,我将如何做类似的事情:

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]'

这里的任何帮助将不胜感激!

4

1 回答 1

1

您可以将此模式与preg_split一起使用

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

或更简单:

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

或者:

$pattern = '~(?=\[)|(?<=])~';
于 2013-07-04T01:59:23.297 回答