PHP正则表达式匹配文件路径

SoL*_*oST 9 php regex preg-match

有人可以帮我这个 preg_match

if (preg_match('~[^A-Za-z0-9_\./\]~', $filepath))
    // Show Error message.
Run Code Online (Sandbox Code Playgroud)

我需要匹配一个可能的文件路径.所以我需要检查双斜线等.有效的文件路径字符串应该只是这样:

mydir/aFile.php
Run Code Online (Sandbox Code Playgroud)

要么

mydir/another_dir/anyfile.js
Run Code Online (Sandbox Code Playgroud)

因此,还应检查此字符串开头的斜杠.请帮忙.

谢谢 :)

编辑:另外,伙计们,这条路径正在文本文件中读取.它不是系统上的文件路径.所以希望在这种情况下它应该能够支持所有系统.

重新编辑:对不起,但字符串也可能看起来像这样: myfile.php或者myfile.js,或者myfile.anything

我如何允许这样的字符串?我为之前没有过于具体而道歉...

小智 14

请注意,有许多类型的可能文件路径.例如:

  • "./"
  • "../"
  • "........"(是的,这可以是文件的名称)
  • "文件/ file.txt的"
  • "文件/文件"
  • "file.txt的"
  • "文件/.././/文件/文件/文件"
  • "/file/.././/file/file/.file"(UNIX)
  • "C:\ Windows \"(Windows)
  • "C:\ Windows\asd/asd"(Windows,php接受此)
  • "文件/.././/文件/文件/文件!@#$"
  • "文件/../.// file/file/file!@#.php.php.php.pdf.php"

所有这些文件路径都有效.我想不出一个可以让它变得完美的简单正则表达式.

让我们假设它现在只是一条UNIX路径,这是我认为应该适用于大多数情况:

preg_match('/^[^*?"<>|:]*$/',$path)
Run Code Online (Sandbox Code Playgroud)

它检查所有字符串是否为^,*,?,",<,>,|,:(对于Windows移除此项).这些都是Windows不允许文件名的字符,以及/和.

如果它是窗口,你应该用/替换路径\,然后将其爆炸并检查它是否是绝对的.这是一个在unix和windows中工作的例子.

function is_filepath($path)
{
    $path = trim($path);
    if(preg_match('/^[^*?"<>|:]*$/',$path)) return true; // good to go

    if(!defined('WINDOWS_SERVER'))
    {
        $tmp = dirname(__FILE__);
        if (strpos($tmp, '/', 0)!==false) define('WINDOWS_SERVER', false);
        else define('WINDOWS_SERVER', true);
    }
    /*first, we need to check if the system is windows*/
    if(WINDOWS_SERVER)
    {
        if(strpos($path, ":") == 1 && preg_match('/[a-zA-Z]/', $path[0])) // check if it's something like C:\
        {
            $tmp = substr($path,2);
            $bool = preg_match('/^[^*?"<>|:]*$/',$tmp);
            return ($bool == 1); // so that it will return only true and false
        }
        return false;
    }
    //else // else is not needed
         return false; // that t
}
Run Code Online (Sandbox Code Playgroud)


cod*_*ict 9

你可以做:

if(preg_match('#^(\w+/){1,2}\w+\.\w+$#',$path)) {
        // valid path.
}else{
        // invalid path
}
Run Code Online (Sandbox Code Playgroud)