Sep

25

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;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

Comments

Name (required)

Email (required)

Website

Speak your mind

2 Comments so far

  1. Matthias Willerich on October 7, 2008 9:34 am

    er… basename() would do it, too, no?

  2. admin on October 9, 2008 10:29 am

    Hi, Matthias

    oops, i didn’t realize that. thanks for the suggestion!

Sponsors




Links