preg_split 忽略括号内

时间:2021-06-20 06:52:00

标签: php regex

id,firstname,addresses{id,city},foo

我想用 , 分割它但不在大括号内,所以输出是

id
firstname
addresses{id,city}
foo

而且我真的在为负面和展望参数而苦苦挣扎。 :(

2 个答案:

答案 0 :(得分:1)

<?php


$re = '/(?:[^,{]|\{[^}]*\})+/';
$str = 'id,firstname,addresses{id,city},foo';

preg_match_all($re, $str, $matches, PREG_PATTERN_ORDER, 0);

// Print the entire match result
var_dump($matches);

Details for the regex

/ (?:[^,{]|\{[^}]*\})+ / g

Non-capturing group (?:[^,{]|\{[^}]*\})+
+ matches the previous token between one and unlimited times, as any times as possible, giving back as needed (greedy)

    1st Alternative [^,{]

        Match a single character not present in the list below [^,{]
        ,{ matches a single character in the list ,{ (case sensitive)

    2nd Alternative \{[^}]*\}
    \{ matches the character { literally (case sensitive)

        Match a single character not present in the list below [^}]
        * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
        } matches the character } literally (case sensitive)
    \} matches the character } literally (case sensitive)

Global pattern flags
    g modifier: global. All matches (don't return after first match)

结果看起来像:Online PHP Sandbox

array(1) {
  [0]=>
  array(4) {
    [0]=>
    string(2) "id"
    [1]=>
    string(9) "firstname"
    [2]=>
    string(18) "addresses{id,city}"
    [3]=>
    string(3) "foo"
  }
}

答案 1 :(得分:0)

使用

{[^{}]*}(*SKIP)(*FAIL)|,

regex proof

解释

--------------------------------------------------------------------------------
  {                        '{'
--------------------------------------------------------------------------------
  [^{}]*                   any character except: '{', '}' (0 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  }                        '}'
--------------------------------------------------------------------------------
  (*SKIP)(*FAIL)           skip & go on searching for the next match
--------------------------------------------------------------------------------
 |                         or
--------------------------------------------------------------------------------
 ,                          a comma

PHP code

<?php
$re = '/{[^{}]*}(*SKIP)(*FAIL)|,/';
$str = 'id,firstname,addresses{id,city},foo';
print_r(preg_split($re, $str));

结果

Array
(
    [0] => id
    [1] => firstname
    [2] => addresses{id,city}
    [3] => foo
)