PHP Case Insensitive Version of file_exists()

后端 未结 14 1507
忘掉有多难
忘掉有多难 2020-11-30 07:47

I\'m trying to think of the fastest way to implement a case insensitive file_exists function in PHP. Is my best bet to enumerate the file in the directory and do a strtolowe

14条回答
  •  感情败类
    2020-11-30 08:13

    My tuned solution, OS independent, case-insensitive realpath() alternative, covering whole path, named realpathi():

    /**
     * Case-insensitive realpath()
     * @param string $path
     * @return string|false
     */
    function realpathi($path)
    {
        $me = __METHOD__;
    
        $path = rtrim(preg_replace('#[/\\\\]+#', DIRECTORY_SEPARATOR, $path), DIRECTORY_SEPARATOR);
        $realPath = realpath($path);
        if ($realPath !== false) {
            return $realPath;
        }
    
        $dir = dirname($path);
        if ($dir === $path) {
            return false;
        }
        $dir = $me($dir);
        if ($dir === false) {
            return false;
        }
    
        $search = strtolower(basename($path));
        $pattern = '';
        for ($pos = 0; $pos < strlen($search); $pos++) {
            $pattern .= sprintf('[%s%s]', $search[$pos], strtoupper($search[$pos]));
        }
        return current(glob($dir . DIRECTORY_SEPARATOR . $pattern));
    }
    

    search filename with glob [nN][aA][mM][eE] pattern seems to be the faster solution

提交回复
热议问题