Regex to get file extensions including tar.gz
Results 1 to 3 of 3

Thread: Regex to get file extensions including tar.gz

  1. #1
    phpMaster
    Join Date
    Jun 2005
    Location
    Europe
    Posts
    3,009

    Regex to get file extensions including tar.gz

    The first regex I have will not work, with a filename like: php-gb_0.8.0.tar.gz

    This is the code I have.
    I have tried to fix it in my own way.
    It seems to work, but there must be a more elegant way.
    With only one regex.
    PHP Code:
        public function getExt()
        {
            
    preg_match("@\.(.+)$@"$this->name$match);
            
    $case1 strtolower($match[1]);
            
    preg_match("@\.(tar.gz)$@"$this->name$match);
            
    $case2 strtolower($match[1]);
            if (
    $case2)
                
    $this->extension $case2;
            else
                
    $this->extension $case1;
            return 
    $this->extension;
        } 
    Apache-2.4.28 (Win64) / PHP-7.1.10 / MySQL-5.7.19 / phpMyAdmin-4.7.4

  2. #2
    phpMaster
    Join Date
    Jun 2005
    Location
    Europe
    Posts
    3,009
    I found a better way.
    I make use of pathinfo() ... with the exception of 'tar.gz'
    PHP Code:
        public function getExt()
        {
            if (
    preg_match("@\.tar.gz$@i"$this->name))
                
    $this->extension 'tar.gz';
            else
                
    $this->extension strtolower(pathinfo($this->namePATHINFO_EXTENSION));
            return 
    $this->extension;
        } 
    Apache-2.4.28 (Win64) / PHP-7.1.10 / MySQL-5.7.19 / phpMyAdmin-4.7.4

  3. #3
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    14,879
    You need another "\" before the second dot, just in case there's a file named "foo.tarxgz".
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

Thread Information

Users Browsing this Thread

There are currently 3 users browsing this thread. (0 members and 3 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •