Jun

27

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

Comments

Name (required)

Email (required)

Website

Speak your mind

2 Comments so far

  1. jakub88 on July 1, 2008 10:10 am

    hi, again, thanks for sharing this great snippet! :)

  2. m0dk1d on July 5, 2008 7:46 pm

    this is pretty short and precise, thanks for posting it here!

Sponsors




Links