这两种括号都是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 包含上面公开的数组列表。