Jump to content

Replace all href's linking to an image


wee493

Recommended Posts

I need to replace all <a href tags linking to an an image because my images are hosted on a different site. For example.

 

I have two links

http://example.com/cool.jpg

http://example.com/file.pdf

 

Currently I use (Something similar to this, this is just to give you an idea)

$link[0] = 'http://example.com/cool.jpg';
$link[1] = 'http://example.com/file.pdf'; 
str_replace ('http://example.com','http://remotesite.com', $links);

 

I need it to only replace the link for images linking to a picture.

 

My links are not in a array they are in a chunk of text so I don't know how to separate out the link.

 

Does anyone have any ideas?

Link to comment
https://forums.phpfreaks.com/topic/175178-replace-all-hrefs-linking-to-an-image/
Share on other sites

$links = preg_replace('~http://example\.com/([^/?].(?:jpg|png|gif|jpgeg))~','http://remotesite.com$1',$links);

 

Just put some more formats in there if you can think of them, I'm a bit sick so I probably can't think of em all

$links = preg_replace('~http://example\.com/([^/?].(?:jpg|png|gif|jpgeg))~','http://remotesite.com$1',$links);

 

Just put some more formats in there if you can think of them, I'm a bit sick so I probably can't think of em all

 

Thanks, does it matter that my images are in folders like, http://example.com/uploads/2009/09 ?

 

I currently working on this code, not having any luck

Are your links inside anchor tags? Would make it easier. But else try something like

 

<?php
$str = 'Text http://example.com/uploads/2009/09/image.jpg and a non-image http://example.com/about/about.php and an image http://example.com/uploads/images/test.name.gif';
$str = preg_replace('~http://example\.com(\S+\.(?:jpe?g|png|gif))~i', 'http://remotesite.com$1', $str);
echo $str;
//Text http://remotesite.com/uploads/2009/09/image.jpg and a non-image http://example.com/about/about.php and an image http://remotesite.com/uploads/images/test.name.gif
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.