note 65383 deleted from function.basename by bjori

From: Date: Sat, 29 Apr 2006 21:17:23 +0000
Subject: note 65383 deleted from function.basename by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-110128@lists.php.net to get a copy of this message
Note Submitter: graham at grahamreeves dot com Reason: bad code ---- I wanted to quickly extract an extension from a filename or url, eg. domain.com/test.gif (the examples are exactly the same if you just submit test.gif) <? // match last *.[a-z] at end of string $Filename = 'domain.com/test.gif'; $regs = array(); $result = ereg( '.\\.([a-zA-Z0-9]+)$', $Filename, $regs ); // no match (therefore no dot or, not dot then alpha numerics), this covers cases like domain.com/sub.dir/test.gif if ( $result == 0 ) return FALSE; // for /domain.com/test.gif // regs[0] will have test.gif // regs[1] will have gif return $regs[1]; ?> Then I have files with "sub-extensions", for example domain.com/test.thumb.gif So I may want to [test for and] extract the thumb part <? // match last *.[a-z].[a-z] at end of string, if only one extension (eg *.[a-z]) then ereg fails $Filename = 'domain.com/test.thumb.gif'; $regs = array(); $result = ereg( '\\.([a-zA-Z0-9]+)\\.([a-zA-Z0-9]+)$', $Filename, $regs ); // no match so either no extension, or only 1 extension if ( $result == 0 ) return FALSE; // for domain.com/test.thumb.gif // regs[0] will have test.thumb.gif // regs[1] will have thumb // regs[2] will have gif return $regs[1]; ?> Hope this helps someone, saves splitting strings and managing resulting arrays :) *note* for the php.net note submission my backslash dot's in my regular expressions weren't showing up, so if the system changes at a later date, it's supposed to be onebackslash dot ([a..... etc, not two backslashes

« previous php.notes (#110128) next »