PHP preg_replace() 编译失败:缺少 )
我有以下函数来返回脚本的干净路径。
function cleanPath($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);
}
PHP 给出错误:
警告:preg_replace() [function.preg-replace]:编译 失败:缺少 ) 位于 C:\wamp\www\extlogin\app\ni\inc\classes\cfiletree.php 线上的偏移量 7 18
关于问题所在以及如何解决它有什么想法吗?
谢谢。
I have the following function to return a clean path for a script.
function cleanPath($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);
}
PHP gives the error:
Warning: preg_replace() [function.preg-replace]: Compilation
failed: missing ) at offset 7 in C:\wamp\www\extlogin\app\ni\inc\classes\cfiletree.php on line
18
Any ideas about what's wrong and how to fix it?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DIRECTORY_SEPARATOR
很可能是\
,这意味着它将转义)
而不是匹配反斜杠。 您需要转义DIRECTORY_SEPARATOR
,使其在正则表达式中变为\\
。对正则表达式中的字符串进行转义的最安全方法是使用
preg_quote
:第二个参数
'#'
是用于正则表达式的分隔符,在您的正则表达式中大小写为#
。Most likely
DIRECTORY_SEPARATOR
is\
which means it'll escape the)
rather than match a backslash. You need to escapeDIRECTORY_SEPARATOR
so that it becomes\\
in the regex.The safest way to escape strings placed in regular expressions is to use
preg_quote
:The second argument,
'#'
, is the separator you use for your regular expression, which in your case is#
.