Preg_match or statement

My code below creates an error, unknown modified "|" ... I am trying to use it as an OR statement. What is the correct way to run this code without errors?

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

Edit

Ok, I changed it a little ... ~(\w+|\(|\)|,)~

Now ... here is the problem: I need to take this line and split it into an array like this:

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

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

thanks

+4
source share
2 answers

You are missing a separator, as @Crayon correctly said, also this template does the same:

 $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] => ) ) 
+1
source

You are missing a separator for your template.

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

+3
source

All Articles