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
),分隔符总是有一个奇数索引。在中间,或者更确切地说是和捕获组。