php preg_match 方括号和括号的组合

php preg_match between Combination of square brackets and brackets

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

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

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

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

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

这个应该适合你:

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

或者像这样

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

两种括号都是meta-characters in regex. If you want to match them you have to 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

工作原理:

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

preg_match() puts in $matches at index 0 the part of the string that matches the entire regex ([{yy}]) and on numeric indices starting with 1 the substrings that match each capturing group.

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

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

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