如何使用正则表达式在php中验证P4路径?
如何在PHP中使用regex验证perforce路径,如下所示 接受路径: //somechars(以//开头,不以/结尾) 以下是有效路径:如何使用正则表达式在php中验证P4路径?,php,regex,Php,Regex,如何在PHP中使用regex验证perforce路径,如下所示 接受路径: //somechars(以//开头,不以/结尾) 以下是有效路径: //depot/abc/pqr/a23/72-32/abc //something //something123 ///depot (has to start with // and more more slashes) //depot/abc/ (cannot end with /) //depot//test (cannot have
//depot/abc/pqr/a23/72-32/abc
//something
//something123
///depot (has to start with // and more more slashes)
//depot/abc/ (cannot end with /)
//depot//test (cannot have // in between)
以下是无效路径:
//depot/abc/pqr/a23/72-32/abc
//something
//something123
///depot (has to start with // and more more slashes)
//depot/abc/ (cannot end with /)
//depot//test (cannot have // in between)
以下是我提出的函数:
public function is_path_valid($path) {
if (!preg_match('/\/\/[A-Za-z0-9\-_\.]+.*[A-Za-z0-9\-_\.]$/',$path) ) {
return false;
}
return true;
}
这是不对的。有人能指出这里出了什么问题吗?您使用的模式匹配:
有一个\/\/[A-Za-z0-9\-\.]+
,后面至少有一个/
。但是,它可以匹配字符串中的任何位置,而不一定是在字符串中[A-Za-z0-9\-.]
中间允许的任何文本。那不是你想要的,是吗*
以其中一个字符结尾(该部分看起来不错)[A-Za-z0-9\-\u\.]$
以下是您应该验证的内容:
它以一个^/
开头(请注意/
与行首的位置相匹配)^
后接一个或多个[-.\w]+
(-..A-Za-z0-9
是\w
)的[A-Za-z0-9.
后跟(?:/[-.\w]+)*
和前面相同的字符,重复0次或更多次(注意/
是a,(?:…)
重复整个组)*
直到行尾$
if (!preg_match('~^//[-.\w]+(?:/[-.\w]+)*$~',$path) ) {
preg_match
将作为第3个参数中数组的独立项返回它(此处不使用)。