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
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

 

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

Link to comment
Share on other sites

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
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.