Page 1 of 1

preg_split regex for file name needed

Posted: Thu Oct 22, 2009 2:03 am
by ViserExcizer
Hello, I need help for a preg split regex, to extract the file name in a given url,

so that http://foo.bar/dadadada.jpg

would return dadadada.jpg

and http://foo.bar/da-da.Da-da.jpg

would return da-da.Da-da.jpg

basically it needs to return the file name no matter what character is in the name, (hyphen, period, comma, underscore)


So far what I did was this, but it isn't working.

Code: Select all

 
 
$string = "http://foo.bar/dadadada.jpg";
 
$keyword = preg_split("#^\w+://\w+\.\w+/([-:a-z0-9]+).(\w+)#i", $string);
 
echo $keyword[0].".".$keyword[1];
 
 
thank you.

Re: preg_split regex for file name needed

Posted: Thu Oct 22, 2009 9:28 am
by ridgerunner
If what you need is to simply get one filename from one string, use preg_match like this:

Code: Select all

if (preg_match('%[^/]+$%m', $text, $matches)) {
    $result = $matches[0];
} else {
    $result = "";
}
The regex matches all non-'/' characters before the end of the line. Simple!

Re: preg_split regex for file name needed

Posted: Thu Oct 22, 2009 11:53 am
by AbraCadaver
I love regex, but why are you using it here?

Code: Select all

$filename = basename('http://foo.bar/dadadada.jpg');