Jun
27
PHP Regex Extract Filename from Full Path
June 27, 2008 |
There are times you may want to extract filenames from their full paths. This example code extracts what looks like a filename from a full path. It makes an assumption that anything after the last directory separator (in this case / ) is the name of a file.
<html>
<head><title></title></head>
<body>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="value" value="<? print $_POST ['value']; ?>"/><br/>
<input type="submit" value="Submit" /><br/><br/>
<?php
if ( $_SERVER['REQUEST_METHOD'] == "POST" )
{
$mystr = $_POST['value'];
if ( ereg( '^\/.*\/([^\/]+)$', $mystr, $matches ) )
{
echo "The file is: $matches[1]";
}
else
{
echo "<b>No file found here.</b>";
}
}
?>
</form>
</body>
</html>
Regular Expression Explanation:
|
^ |
the beginning of the line, followed by … |
|
\/ |
a slash, then … |
|
. |
any character … |
|
+ |
found one or more times, up to … |
|
\/ |
a slash, followed by … |
|
( |
the beginning of the group that will capture the filename and contains … |
|
[ |
a character class that contains … |
|
^ |
anything that isn't … |
|
\/ |
a slash … |
|
] |
the end of the character class … |
|
+ |
found one or more times … |
|
) |
the end of the group, which goes up to … |
|
$ |
the end of the line … |
Similar Posts
- PHP Regex - Extract Filenames from Full Path
- PHP Regex Extract Directiory from Full Path
- PHP Regex - Validate Email Address
- Validate URL Using PHP Regex
- PHP Regex Extract Username from Email Address
- PHP Regex Validate IP address
- PHP Regex Remove Whitespace from HTML
Comments
2 Comments so far



































hi, again, thanks for sharing this great snippet! :)
this is pretty short and precise, thanks for posting it here!