如何使用正则表达式在php中验证P4路径?

如何使用正则表达式在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

如何在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 // 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,
    *
    重复整个组)
  • $
    直到行尾
Regex:

if (!preg_match('~^//[-.\w]+(?:/[-.\w]+)*$~',$path) ) {

比我快,而且描述的内容比我一开始添加的还要多!非常好+1谢谢。什么是“?:”的正则表达式语法。考虑<代码>(?:fo)< /> >与<代码>(fo)< /> >相同,只是它不存储不必要的数据。如果它是一个正常组,
preg_match
将作为第3个参数中数组的独立项返回它(此处不使用)。