微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – regexp使用逗号(,)分隔符分割字符串,但如果逗号是大括号{,}则忽略

我需要一个正则表达式来使用逗号(,)分隔符来分割字符串,但是如果逗号在下面的示例中是花括号{,}则忽略;

"asd", domain={"id"="test"}, names={"index"="user.all", "show"="user.view"}, test="test"

INTO(应该是)

"asd"
domain={"id"="test"}
names={"index"="user.all", "show"="user.view"}
test="test"

问题:(不是这个)

"asd"
domain={"id"="test"}
names={"index"="user.all"
"show"="user.view"}
test="test"

我尝试了这个,但它也在括号内分隔逗号{,}

\{[^}]*}|[^,]+

但我完全不知道这应该如何最终结束.
任何帮助都会得到满足!

解决方法:

我看到了可能性(不会因长字符串而崩溃):

一个使用preg_match_all:

$pattern = '~
(?:
    \G(?!\A), # contigous to the prevIoUs match, not at the start of the string
  |           # OR
    \A ,??    # at the start of the string or after the first match when
              # it is empty
)\K           # discard characters on the left from match result
[^{,]*+       # all that is not a { or a ,
(?:
    {[^}]*}? [^{,]* # a string enclosed between curly brackets until a , or a {
                    # or an unclosed opening curly bracket until the end
)*+
~sx';

if (preg_match_all($pattern, $str, $m))
    print_r($m[0]);

第二个使用preg_split和backtracking控制动词来避免大括号之间的部分(较短但效率较低的长字符串):

$pattern = '~{[^}]*}?(*SKIP)(*F)|,~';
print_r(preg_split($pattern, $str));

(* F)强制模式失败并且(* SKIP)强制正则表达式引擎跳过模式失败时已经匹配的部分.

最后一种方法的缺点是模式以交替开始.这意味着对于不是{或a}的每个字符,都会测试交替的两个分支(什么都不是).但是,您可以使用S(学习)修改器改进模式:

$pattern = '~{[^}]*}?(*SKIP)(*F)|,~S';

或者您可以在没有替换的情况下编写它,如下所示:

$pattern = '~[{,](?:(?<={)[^}]*}?(*SKIP)(*F))?~';

以这种方式,具有{或者之前使用比正则动态引擎的正常步行更快的算法搜索的位置.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐