简体   繁体   English

preg_match 或运算符

[英]preg_match or operator

My code below produces an error, unknown modified "|"... I'm trying to use it as the OR operator.我下面的代码产生一个错误,未知的修改“|”......我正在尝试将它用作 OR 运算符。 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+|\(|\)|,)~好吧我稍微改了一下... ~(\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谢谢

You are missing the delimiter for your pattern.您缺少模式的分隔符。

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

You're missing the delimiter as @Crayon correctly mentioned, also this pattern does the same thing:你错过了@Crayon正确提到的分隔符,这个模式也做同样的事情:

$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: 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] => )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM