分隔符
当使用 PCRE 函数的时候,模式需要由分隔符闭合包裹。 分隔符可以是任意非字母数字、非反斜线、非空白字符。 静默忽略合法分隔符之前的空白字符。
经常使用的分隔符是正斜线(/
)、hash符号(#
)
以及取反符号(~
)。下面的例子都是使用合法分隔符的模式。
/foo bar/ #^[^0-9]$# +php+ %[a-zA-Z0-9_-]%
It is also possible to use
bracket style delimiters where the opening and closing brackets are the
starting and ending delimiter, respectively. ()
,
{}
, []
and <>
are all valid bracket style delimiter pairs.
(this [is] a (pattern)) {this [is] a (pattern)} [this [is] a (pattern)] <this [is] a (pattern)>
如果需要在正则模式内匹配分隔符,必须使用反斜线转义。如果分隔符经常在 正则模式内出现, 最好使用其他分隔符以便提高可读性。
/http:\/\// #http://#
可以在结束分隔符后面增加模式修饰符。 下面的例子是一个大小写不敏感的匹配:
#[a-z]#i
+添加备注
用户贡献的备注 3 notes
Pedro Gimeno ¶
9 years ago
Note that bracket style opening and closing delimiters aren't a 100% problem-free solution, as they need to be escaped when they aren't in matching pairs within the expression. That mismatch can happen when they appear inside character classes [...], as most meta-characters lose their special meaning. Consider these examples:
<?php
preg_match('{[{]}', ''); // Warning: preg_match(): No ending matching delimiter '}'
preg_match('{[}]}', ''); // Warning: preg_match(): Unknown modifier ']'
preg_match('{[}{]}', ''); // Warning: preg_match(): Unknown modifier ']'
?>
Escaping them solves it:
<?php
preg_match('{[\{]}', ''); // OK
preg_match('{[}]}', ''); // OK
preg_match('{[\}\{]}', ''); // OK
?>
备份地址:http://www.lvesu.com/blog/php/regexp.reference.delimiters.php