preg_split regex for file name needed

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
ViserExcizer
Forum Newbie
Posts: 24
Joined: Tue Nov 25, 2008 1:17 pm

preg_split regex for file name needed

Post 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.
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: preg_split regex for file name needed

Post 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!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: preg_split regex for file name needed

Post by AbraCadaver »

I love regex, but why are you using it here?

Code: Select all

$filename = basename('http://foo.bar/dadadada.jpg');
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply