Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用preg split获取分隔符数组_Php_Preg Split - Fatal编程技术网

Php 使用preg split获取分隔符数组

Php 使用preg split获取分隔符数组,php,preg-split,Php,Preg Split,字符串: "test AND test2 OR test3 AND test4" PHP: preg_split(\s?AND\s?|\s?OR\s?, $string); 结果: ["test", "test2", "test3", "test4"] ["test", "test2", "test3", "test4"] ["AND", "OR", "AND"] 想要的结果: ["test", "test2", "test3", "test4"] ["test", "test2",

字符串:

"test AND test2 OR test3 AND test4"
PHP:

preg_split(\s?AND\s?|\s?OR\s?, $string);
结果:

["test", "test2", "test3", "test4"]
["test", "test2", "test3", "test4"]
["AND", "OR", "AND"]
想要的结果:

["test", "test2", "test3", "test4"]
["test", "test2", "test3", "test4"]
["AND", "OR", "AND"]

如何获得此结果?

您可以使用
preg\u split
preg\u match\u all
作为

$str = "test AND test2 OR test3 AND test4";
$arr1 = preg_split('/\b(AND|OR)\b/', $str);
preg_match_all('/\b(AND|OR)\b/', $str, $arr2);
print_r($arr1);
print_r($arr2[0]);


否则,只需使用
preg_split_DELIM_CAPTURE
选项使用
preg_split_DELIM_CAPTURE
时,使用分离捕获分隔符的方法所建议的答案即可

$string = "test AND test2 OR test3 AND test4";

$arr = preg_split('~\s*\b(AND|OR)\b\s*~', $string, -1, PREG_SPLIT_DELIM_CAPTURE);

$andor = [];
$test = [];

foreach($arr as $k=>$v) {
    if ($k & 1)
        $andor[] = $v;
    else
        $test[] = $v;
}

print_r($test);
print_r($andor);
$k&1
是按位运算符和。当索引
$k
为奇数时,这意味着第一位设置为1,然后
$k&1
返回
1
。(除非您使用
PREG\u SPLIT\u NO\u EMPTY
),分隔符总是有一个奇数索引。

在中间,或者更确切地说是和捕获组。