I need to make next feature on my site: user writing an article and attach image in it, images are often stored not on localhost. I need to download this images to localhost and replace links to localhost images.
For example:
<img ... src="http://bob.com/img/image1.png" ... >
<img ... src="http://bob.com/img/image2.png" .... >
Script will find src
content, download images and replace it like this:
<img ... src="/images/image1.png" ... >
<img ... src="/images/image2.png" .... >
I understand how to parse all src
from code:
$subject = # i will put there article content (with img tags etc)
$result = array();
preg_match("/<img.*?src="(.*?)".*?>/", $subject, $result);
Now $result
array will contain all link to images. Nice. Now I have some questions.
1) If I use preg_replace
, will it help me to solve this task? In my opinion not, because preg_replace
will replace content instantly (so I can't download image, create new link for stored on localhost image and somehow set this as argument for preg_replace
, because it is run yet). Am I right with this assumption?
2) Okay. I can form an array, like I said. After that I download all images from this array. After that, somehow, I will replace all old images, for new images. I think it is more realistic. Am I right?
Something like that:
$subject = # i will put there article content (with img tags etc)
$result = array();
preg_match("/<img.*?src="(.*?)".*?>/", $subject, $result);
foreach($result as $src)
{
$new_src = downloadImage($src);
# somehow replace old image with new image there. How?
}
3) How exactly I can replace links if I will use 2nd method?