note 89127 deleted from function.basename by googleguy
| From: | googleguy@php.net | Date: | Tue, 22 Oct 2013 08:03:55 +0000 |
| Subject: | note 89127 deleted from function.basename by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-196784@lists.php.net to get a copy of this message | ||
Note Submitter: info at smaartweb dot com
----
here are two good functions to extract the filename and extension part from any given path or url.
<?php
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
<?php
//$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);
?>