我的代码产生错误,未知修改“|”...我正在尝试将其用作OR运算符。运行此代码没有错误的正确方法是什么?
$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 );
有人可以帮我这么做吗?当我运行上面的表达式时,它输出一个空数组....
由于
答案 0 :(得分:3)
您缺少模式的分隔符。
$p = "~(\w+)|(\()|(\))|(\,)~";
答案 1 :(得分:1)
你错过了@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] => )
)