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 t开发者_运维技巧he 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:
$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] => )
)
精彩评论