PHP Case Insensitive Version of file_exists()

后端 未结 14 1342
忘掉有多难
忘掉有多难 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:33

    Just ran across this today, but didn't like any of the answers here, so I thought I would add my solution ( using SPL and the regex iterator )

    function _file_exists( $pathname ){
        if(file_exists($pathname)) return $pathname;
    
        try{
            $path = dirname( $pathname );
            $file = basename( $pathname );
    
            $Dir = new \FilesystemIterator( $path, \FilesystemIterator::UNIX_PATHS );
            $regX = new \RegexIterator($Dir, '/(.+\/'.preg_quote( $file ).')$/i', \RegexIterator::MATCH);
    
            foreach ( $regX as $p ) return $p->getPathname();
    
        }catch (\UnexpectedValueException $e ){
            //invalid path
        }
        return false;
    }
    

    The way I am using it is like so:

     $filepath = 'path/to/file.php';
    
     if( false !== ( $filepath = _file_exists( $filepath ))){
          //do something with $filepath
     }
    

    This way it will use the built in one first, if that fails it will use the insensitive one, and assign the proper casing to the $filepath variable.

    0 讨论(0)
  • 2020-11-30 08:37

    I tuned the function a lil bit more. guess this better for use

    function fileExists( $fileName, $fullpath = false, $caseInsensitive = false ) 
    {
        // Presets
        $status         = false;
        $directoryName  = dirname( $fileName );
        $fileArray      = glob( $directoryName . '/*', GLOB_NOSORT );
        $i              = ( $caseInsensitive ) ? "i" : "";
    
        // Stringcheck
        if ( preg_match( "/\\\|\//", $fileName) ) // Check if \ is in the string
        {
            $array    = preg_split("/\\\|\//", $fileName);
            $fileName = $array[ count( $array ) -1 ];
        }
    
        // Compare String
        foreach ( $fileArray  AS $file )
        {
            if(preg_match("/{$fileName}/{$i}", $file))
            {
                $output = "{$directoryName}/{$fileName}";
                $status = true;
                break;
            }
        }
    
        // Show full path
        if( $fullpath && $status )
            $status = $output;
    
        // Return the result [true/false/fullpath (only if result isn't false)]
        return $status;
    }
    
    0 讨论(0)
提交回复
热议问题