Php regexp使用逗号(,)分隔符拆分字符串,但如果逗号在大括号中则忽略{,}
我需要一个regexp来使用逗号(,)分隔符分割字符串,但在下面的示例中,如果逗号位于大括号{,}中,则忽略它Php regexp使用逗号(,)分隔符拆分字符串,但如果逗号在大括号中则忽略{,},php,preg-split,Php,Preg Split,我需要一个regexp来使用逗号(,)分隔符分割字符串,但在下面的示例中,如果逗号位于大括号{,}中,则忽略它 "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_split
您可以像
echo preg_split('/(,)(?=(?:[^}]|{[^{]*})*$)/',$your_string);
我看到了各种可能性(不会因为长字符串而崩溃):
第一个带有preg\u match\u 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
和回溯控制动词,以避免将部分括在花括号中(较短,但对于长字符串效率较低):
(*F)
强制模式失败,(*SKIP)
强制正则表达式引擎在模式失败时跳过已匹配的部分
最后一种方法的缺点是模式从交替开始。这意味着,对于不是{
或,
的每个字符,交替的两个分支都会进行测试(没有任何结果)。但是,您可以使用S
(研究)修饰符改进模式:
$pattern = '~{[^}]*}?(*SKIP)(*F)|,~S';
或者你可以不加修改地写,就像这样:
$pattern = '~[{,](?:(?<={)[^}]*}?(*SKIP)(*F))?~';
$pattern='~[{,](?:(?我想再问一件事,因为你似乎很擅长regexp,如果你不介意回答的话……我怎么能排除呢?name={“index”=“user.all”,“show”=“user.view”}来自“asd”,domain={“id”=“test”},name={“index”=“user.all”,“show”=“user.view”},test={大括号形式应该被忽略,其余的用逗号解析delimiter@Oguzhan:您所要求的内容超出了正则表达式的范围,您需要使用SQL解析器。
$pattern = '~{[^}]*}?(*SKIP)(*F)|,~';
print_r(preg_split($pattern, $str));
$pattern = '~{[^}]*}?(*SKIP)(*F)|,~S';
$pattern = '~[{,](?:(?<={)[^}]*}?(*SKIP)(*F))?~';