一些 javascript 实现允许 [] 和 [^] 分别作为 "no character" 和 "any character"。但请记住,这是 javascript 正则表达式特有的。 (如果您对此主题感兴趣,可以查看this post。)
换句话说,[^] 是 [\s\S] 的快捷方式,因为 javascript 没有点可以匹配换行符的 dotall 或 singleline 模式。
因此,要在 PHP 中获得相同的结果,您必须将 [^] 替换为 .(默认匹配除换行符之外的任何字符),在结束分隔符之后使用单行修饰符 s 或在 @ 之前使用 (?s) 987654330@ 也允许换行。示例:/.+/s 或 /(?s).+/
但对于您的特定情况,这种模式似乎更合适:
preg_match_all('~((?>[^rn\\\:]++|(?<!\\\)[rn])+):([^\\\]++)~', $subject, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo $match[1].' '.$match[2].'<br/>';
}
模式说明:
~ # pattern delimiter
( # open the first capturing group
(?> # open an atomic group
[^rn\\\:]++ # all characters that are not "r", "n", "\" or ":"
| # OR
(?<!\\\)[rn] # "r" or "n" not preceded by "\"
)+ # close the atomic group and repeat one or more times
) # close the first capturing group
:
( # open the second capturing group
[^\\\]++ # all characters except "\" one or more times
) # close the second capturing group
~
注意事项:
当您想在用单引号括起来的字符串中表示\(反斜杠)时,必须使用双转义符:\\\
这种模式的原理是使用否定字符类和否定断言,换句话说,它查找所需的子字符串不能是什么。
上述模式使用原子组(?>...) 和所有格量词++ 代替非捕获组(?:...) 和简单量词+。除了正则表达式引擎在原子组和所有格量词失败时无法返回测试其他方式外,其他方式相同,因为它不记录回溯位置。借助此类功能,您可以在性能上取胜。