PHP Case Insensitive Version of file_exists()

后端 未结 14 1492
忘掉有多难
忘掉有多难 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.

提交回复
热议问题