Sep
25
PHP Regex - Extract Filenames from Full Path
September 25, 2008 |
PHP Regular Expression (Regex) can do a lot wonders, one is to extract what looks like a filename from a full path. It makes an assumption that anything after the last directory separator (in this case a slash: / ) is the name of a file.
Below is the code:
<html>
<head><title>Extract Filenames from Full Path</title></head>
<body>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post"&amp;amp;amp;amp;amp;amp;
<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 Filename from Full Path
- PHP Regex Extract Directiory from Full Path
- PHP Regex - Validate Email Address
- PHP Regex Extract Username from Email Address
- Validate URL Using PHP Regex
- PHP Regex Validate IP address
- PHP Regex Remove Whitespace from HTML
Comments
2 Comments so far



































er… basename() would do it, too, no?
Hi, Matthias
oops, i didn’t realize that. thanks for the suggestion!