Preg_Match或运算符
我的下面的代码产生一个错误,未知修改的"|"...我正试着用它做手术室的操作员。运行此代码而不出错的正确方法是什么?
$p = "(w+)|(()|())|(,)";
$s = "sum(blue,paper,green(yellow,4,toast)))";
preg_match($p,$s, $matches);
print_r($matches);
编辑
好的,我稍微改了一下……~(w+|(|)|,)~
array("sum","(","blue","paper","green","(" ... etc );
有人能帮我吗?当我运行上面的表达式时,它输出一个空数组...
谢谢
解决方案
您遗漏了@Crayon正确提到的分隔符,此模式也执行相同的操作:
$p = '~(w+|[(]|[)]|,)~';
对于您的(新)问题,try this:
$p = '~([(),])~';
$str = 'sum(blue,paper,green(yellow,4,toast)))';
$res = preg_split($p, $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($res);
输出:
Array
(
[0] => sum
[1] => (
[2] => blue
[3] => ,
[4] => paper
[5] => ,
[6] => green
[7] => (
[8] => yellow
[9] => ,
[10] => 4
[11] => ,
[12] => toast
[13] => )
[14] => )
[15] => )
)
相关文章