PHP preg_replace 错误
我有以下代码:
protected function safePath($path) {
$path = (string) $path;
$path = preg_replace(
array(
'#[\n\r\t\0]*#im',
'#/(\.){1,}/#i',
'#(\.){2,}#i',
'#(\.){2,}#i',
'#\('.DIRECTORY_SEPARATOR.'){2,}#i'
),
array(
'',
'',
'',
'/'
),
$path
)
;
return rtrim($path,DIRECTORY_SEPARATOR);
}
在使用路径执行函数后,出现此错误:
警告:preg_replace()[function.preg-replace]:编译失败:<中偏移量3处的括号不匹配b>....../myfile.php 位于 534
行,
其中第 534 行是此处标有的行:
protected function safePath($path) {
$path = (string) $path;
$path = preg_replace(
array(
'#[\n\r\t\0]*#im',
'#/(\.){1,}/#i',
'#(\.){2,}#i',
'#(\.){2,}#i',
'#\('.DIRECTORY_SEPARATOR.'){2,}#i'
),
array(
'',
'',
'',
'/'
), <---------------- THis is line 534
$path
)
;
return rtrim($path,DIRECTORY_SEPARATOR);
}
修复此错误有任何帮助吗?谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在最后的正则表达式中,您已经转义了左括号,但不是右括号
可能应该是...
...或者斜杠可能根本不应该在那里。无论哪种方式,其不一致。
in the final regex, you've escaped the opening parenthesis but not the closing one
should perhaps be...
...or perhaps the slash shouldn't be there at all. Either way, its inconsistent.
这是因为这部分就在这里:
我猜你使用的是 Linux 系统。在 Windows 上,DIRECTORY_SEPARATOR 是一个反斜杠,它与该行上的初始反斜杠匹配。
在 Linux 上,DIRECTORY_SEPARATOR 是正斜杠,因此该字符串在开头有一个转义的左括号,而在结尾处没有匹配的括号。
您可以通过简单地用
/
或\
替换该行上的 DIRECTORY_SEPARATOR 来在任一类型的操作系统上重现该错误。您将立即看到结果。It's because of this part right here:
I'm guessing you're on a linux system. On Windows, the DIRECTORY_SEPARATOR is a backslash, which matches with the initial backslash you have on that line.
On linux, the DIRECTORY_SEPARATOR is a forward slash, and therefore this string has an escaped left bracket at the start, and no matching bracket at the end.
You can reproduce the error on either type of OS by simply replacing the DIRECTORY_SEPARATOR on that line with either a
/
or a\
. You'll see the result right away.很奇怪,如果两个 parethesees 都被转义,我只能得到这个错误:
也许是因为你没有转义 DIRECTORY_SEPARATOR ?
Mighty odd, I can only get that error if both parethesees are escaped:
Maybe because you are not escaping the DIRECTORY_SEPARATOR ?