php preg_match在方括号和括号的组合之间

时间:2018-01-27 14:17:48

标签: php preg-match preg-split

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

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

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

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

换句话说,它剥去了支架。我仍然对正则表达式感到困惑,但发现有时preg match是更简单的解决方案。寻找其他例子但不符合我的需要。

3 个答案:

答案 0 :(得分:2)

这个应该适合你:

@angular/cli: 1.4.2
node: 6.10.3
os: win32 x64
@angular/animations: 4.4.5
@angular/common: 4.4.5
@angular/compiler: 4.4.5
@angular/core: 4.4.5
@angular/forms: 4.4.5
@angular/http: 4.4.5
@angular/platform-browser: 4.4.5
@angular/platform-browser-dynamic: 4.4.5
@angular/router: 4.4.5
@angular/cli: 1.4.2
@angular/compiler-cli: 4.4.5
@angular/language-service: 4.4.5
typescript: 2.3.4

答案 1 :(得分:1)

或者像这样

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

答案 2 :(得分:1)

regex中的两种括号均为meta-characters。如果你想匹配它们,你必须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

工作原理:

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

preg_match()$matches放在索引0的字符串中与整个regex[{yy}])匹配的部分以及以{开头的数字索引{1}}与每个capturing group匹配的子字符串。

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

[{...}]

当第四个参数为preg_match_all('/\[\{([^\]}]*)}]/', $varx, $matches, PREG_SET_ORDER); 时,PREG_SET_ORDER包含上面公开的数组列表。