Ilija Petkovic
Ilija Petkovic

Reputation: 143

preg_match and images URL

I have a little problem with preg_match function in PHP. I think that I never will learn how to use this function. I want to extract URL of image from HTML without name of image. For example, if I have some link for image:

"/data/images/2013-10-03/someimage.jpg"

or

"http://something.com//data/images/2013-10-03/someimage.jpg"

How can I use preg_match function to delete everything left of last forward slash, so I can get only image name from URL?

Maybe it's smarter to use different function but I dont know which one?

P.S. Can you give me some good tutorial for preg_match function?

Maybe I forgot to say... I dont know how long is image name or what is image name exactly. I need function for extract only what is on right side from last forward slash.

Upvotes: 1

Views: 7522

Answers (4)

AbraCadaver
AbraCadaver

Reputation: 79024

No need for regex or anything fancy:

$var = "http://something.com/data/images/2013-10-03/someimage.jpg";

$image = basename($var);

Upvotes: 6

Bogdan Solomykin
Bogdan Solomykin

Reputation: 176

$pattern = '/[\w\-]+\.(jpg|png|gif|jpeg)/';
$subject = 'http://something.com//data/images/2013-10-03/someimage.png';
$result = preg_match($pattern, $subject, $matches);
echo $matches[0]; //someimage.jpg

Upvotes: 6

user1727533
user1727533

Reputation:

You can use Simple HTML DOM Parser to get href between the a tags. For example:

foreach($html->find('a.[class="your class"]') as $var) // echo "href." >sometext
";

hope this helps!

Upvotes: 1

fdrv
fdrv

Reputation: 890

U need use preg_replace() and u can try use online for play with regular, it is a fast way to learn regex. http://preg_replace.onlinephpfunctions.com/

For example: /\/someimage.jpg/ replace on ''(null).

It will return http://something.com//data/images/2013-10-03 from http://something.com//data/images/2013-10-03/someimage.jpg.

Upvotes: 1

Related Questions