note 89127 added to function.basename
| From: | info at smaartweb dot com | Date: | Mon, 23 Feb 2009 16:38:46 +0000 |
| Subject: | note 89127 added to function.basename | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-151019@lists.php.net to get a copy of this message | ||
here are two good functions to extract the filename and extension part from any given path or url.
function ShowFileExtension($filepath)
{
preg_match('/[^?]*/', $filepath, $matches);
$string = $matches[0];
$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
# check if there is any extension
if(count($pattern) == 1)
{
echo 'No File Extension Present';
exit;
}
if(count($pattern) > 1)
{
$filenamepart = $pattern[count($pattern)-1][0];
preg_match('/[^?]*/', $filenamepart, $matches);
echo $matches[0];
}
}
function ShowFileName($filepath)
{
preg_match('/[^?]*/', $filepath, $matches);
$string = $matches[0];
#split the string by the literal dot in the filename
$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
#get the last dot position
$lastdot = $pattern[count($pattern)-1][1];
#now extract the filename using the basename function
$filename = basename(substr($string, 0, $lastdot-1));
#return the filename part
return $filename;
}
usage
//$string = 'C:\My Documents\My Name\filename.ext';
//$string = 'http://php.net/manual/add-note.php?
&redirect=http://php.net/function.basename.php';
echo ShowFileName($string);
echo ShowFileExtension($string);
----
Server IP: 59.162.86.33
Probable Submitter: 59.96.132.164
----
Manual Page -- http://www.php.net/manual/en/function.basename.php
Edit -- https://master.php.net/note/edit/89127
Del: integrated -- https://master.php.net/note/delete/89127/integrated
Del: useless -- https://master.php.net/note/delete/89127/useless
Del: bad code -- https://master.php.net/note/delete/89127/bad+code
Del: spam -- https://master.php.net/note/delete/89127/spam
Del: non-english -- https://master.php.net/note/delete/89127/non-english
Del: in docs -- https://master.php.net/note/delete/89127/in+docs
Del: other reasons-- https://master.php.net/note/delete/89127
Reject -- https://master.php.net/note/reject/89127
Search -- https://master.php.net/manage/user-notes.php