gpt4 book ai didi

php - 正则表达式基于和/或在搜索概念中中断字符串

转载 作者:行者123 更新时间:2023-12-01 16:43:09 26 4
gpt4 key购买 nike

您好,我正在尝试创建正则表达式,但遇到了问题。

基本上这就是我所拥有的:

(.+?)(and|or)(.+?)

我正在寻找的例子:

(user email ends with "@email.com" and user name is "John") or (user email ends with "@domain.com" and user name is "Bob")

我想要的预期结果是:

(user email ends with "@email.com" and user name is "John")
(user email ends with "@domain.com" and user name is "Bob")

基本上,OR 将根据可选的“()”进行拆分,因此我可以拥有类似的内容

user email ends with "@email.com" and user name is "John"

我期待的是这样的:

user email ends with "@email.com"
user name is "John"

如果我必须有多个正则表达式,那么最终目标就是上面这样的:

Array
(
[0] => Array
(
[0] => user email ends with "@email.com"
[1] => user name is "John"
)

[1] => Array
(
[0] => user email ends with "@domain.com"
[1] => user name is "Bob"
)
)

如果是这样

(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))

然后我会期待这样的事情

Array
(
[0] => Array
(
[0] => user email ends with "@email.com"
[1] => user name is "John"
)

[1] => Array
(
[0] => user email ends with "@domain.com"
[1] => user name is "Bob"
[2] => Array
(
[0] => user id is 5
)
)
)

任何帮助将不胜感激!

最佳答案

这是一个递归函数,它也使用递归正则表达式,让我们递归吧!!!

$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);
}
}

输出:

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

关于php - 正则表达式基于和/或在搜索概念中中断字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23376145/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com