【问题标题】:php preg_match between Combination of square brackets and bracketsphp preg_match 方括号和方括号的组合
【发布时间】:2018-01-27 14:17:48
【问题描述】:

我想使用 preg_match 来查找 [{}] 之间的文本,例如:$varx = "[{xx}]";

最终输出将是 $match = 'xx';

另一个例子 $varx = "bla bla [{yy}] bla bla";

最终输出将是这样的 $match = 'yy';

换句话说,它去掉了括号。我仍然对正则表达式感到困惑,但发现有时 preg 匹配是更简单的解决方案。搜索其他示例但不符合我的需要。

【问题讨论】:

    标签: php preg-match preg-split


    【解决方案1】:

    这个应该适合你:

    preg_match('/\[\{([^\]\}]+)\}\]/', $varx, $match);
    

    【讨论】:

      【解决方案2】:

      这两种括号都是meta-characters in regex。如果你想匹配它们,你必须escape them(转义左括号就足够了):

      $varx = "bla bla [{yy}] bla bla";
      preg_match('/\[\{([^\]}]*)}]/', $varx, $matches);
      print_r($matches);
      

      它显示:

      Array
      (
          [0] => [{yy}]
          [1] => yy
      ) 
      

      regex:

      /           # delimiter; it is not part of the regex but separates it 
                  #      from the modifiers (no modifiers are used in this example);
      \[          # escaped '[' to match literal '[' and not use its special meaning
      \{          # escaped '{' to match literal '{' and not use its special meaning
      (           # start of a group (special meaning of '(' when not escaped)
         [^       # character class, excluding (special meaning of '[' when not escaped)
              \]  # escaped ']' to match literal ']' (otherwise it means end of class)
              }   # literal '}'
         ]        # end of the character class
         *        # repeat the previous expression zero or more times
      )           # end of group
      }]          # literal '}' followed by ']'
      /           # delimiter
      

      工作原理:

      它匹配[{字符序列(\[\{)后跟零个或多个(*)字符(^)不是类([...]),然后是}] .该类包含两个字符(]}),[{}] 之间的所有内容都包含在一个捕获组中((...))。

      preg_match()$matches 放入索引0 匹配整个regex ([{yy}]) 的字符串部分和以1 开头的数字索引上匹配每个capturing group 的子字符串.

      如果输入字符串包含多个要匹配的[{...}] 块,则必须使用preg_match_all()

      preg_match_all('/\[\{([^\]}]*)}]/', $varx, $matches, PREG_SET_ORDER);
      

      当第四个参数是PREG_SET_ORDER 时,$matches 包含上面公开的数组列表。

      【讨论】:

        【解决方案3】:

        或者像这样

        preg_match('/(?<=\[\{).*?(?=\}\])/', $varx, $match);

        【讨论】:

        • 如果像bla bla [{yy}] bla bla bla bla [{yy}] bla bla这样的一行中有超过1个[{yy}],这将不起作用
        • 非常感谢你是对的。我编辑了我的答案现在它可以工作了
        猜你喜欢
        • 1970-01-01
        • 2022-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-11
        • 2012-09-17
        • 2012-02-25
        相关资源
        最近更新 更多