note 89127 modified in function.basename by danbrown
| From: | danbrown@php.net | Date: | Mon, 23 Feb 2009 16:40:57 +0000 |
| Subject: | note 89127 modified in function.basename by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-151020@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.
<?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);
?>
--was--
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);
http://php.net/manual/en/function.basename.php