Hi I am trying to create regex expression and I am running into problems.
Basically this is what I have:
(.+?)(and|or)(.+?)
What I
Here's a recursive function which also uses a recursive regex, let's recurse!!!
$text = '(user email ends with "@email.com" and user name is "John") or ((user email ends with "@domain.com" and user name is "Bob") or (user id is 5))';
print_r(buildtree($text));
function buildtree($input){
$regex = <<<'regex'
~( # Group 1
\( # Opening bracket
( # Group 2
(?: # Non-capturing group
[^()] # Match anything except opening or closing parentheses
| # Or
(?1) # Repeat Group 1
)* # Repeat the non-capturing group zero or more times
) # End of group 2
\) # Closing bracket
)~x
regex;
// The x modifier is for this nice and fancy spacing/formatting
$output = [];
if(preg_match_all($regex, $input, $m)){ // If there is a match
foreach($m[2] as $expression){ // We loop through it
$output[] = buildtree($expression); // And build the tree, recursive !!!
}
return $output;
}else{ // If there is no match, we just split
return preg_split('~\s*(?:or|and)\s*~i', $input);
}
}
Output:
Array
(
[0] => Array
(
[0] => user email ends with "@email.com"
[1] => user name is "John"
)
[1] => Array
(
[0] => Array
(
[0] => user email ends with "@domain.com"
[1] => user name is "Bob"
)
[1] => Array
(
[0] => user id is 5
)
)
)
Online php demo Online regex demo