preg_match or operator

旧时模样 提交于 2020-01-14 10:46:28

问题


My code below produces an error, unknown modified "|"... I'm trying to use it as the OR operator. What is the correct way to run this code without error?

$p = "(\w+)|(\()|(\))|(\,)";
$s =  "sum(blue,paper,green(yellow,4,toast)))";
preg_match($p,$s, $matches);
print_r($matches);

Edit

Okay I changed it a bit... ~(\w+|\(|\)|,)~

Now... here's the problem: I need to take that string and split it into an array like this:

array("sum","(","blue","paper","green","(" ... etc );

Can someone help me do that? when I run the above expression it outputs an empty array....

Thanks


回答1:


You're missing the delimiter as @Crayon correctly mentioned, also this pattern does the same thing:

$p = '~(\w+|[(]|[)]|,)~';

As for your (new) problem, 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);

Output:

Array
(
    [0] => sum
    [1] => (
    [2] => blue
    [3] => ,
    [4] => paper
    [5] => ,
    [6] => green
    [7] => (
    [8] => yellow
    [9] => ,
    [10] => 4
    [11] => ,
    [12] => toast
    [13] => )
    [14] => )
    [15] => )
)



回答2:


You are missing the delimiter for your pattern.

$p = "~(\w+)|(\()|(\))|(\,)~";



来源:https://stackoverflow.com/questions/5846552/preg-match-or-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!