正则表达式,解析img src内容并用另一个链接替换它 [英] Regular expression, parsing img src content and replacing it with another links
问题描述
我需要在我的网站上创建下一个功能:用户写文章并在其中添加图像,图像通常不会存储在本地主机上。我需要将这些图像下载到本地主机,并将链接替换为本地图像。
例如:
< img ... src =http://bob.com/img/image1.png...>
< img ... src =http://bob.com/img/image2.png....>
脚本会找到 src
内容,下载图片并将其替换为:
< img ... src =/ images / image1.png...> ;
< img ... src =/ images / image2.png....>
我理解如何解析所有 src
代码:
$ subject =#我会在那里放置文章内容(使用img标签等)
$ result = array ();
preg_match(/< img。*?src =(。*?)。*?> /,$ subject,$ result);
现在 $ result
数组将包含所有链接图像。尼斯。现在我有一些问题。
$ b
1)如果我使用 preg_replace
,它会帮我解决这个任务?在我看来不是,因为 preg_replace
会立即替换内容(所以我不能下载镜像,创建新的链接存储在本地主机映像上,并以某种方式将其设置为 preg_replace
,因为它还在运行)。我对这个假设是否正确?
2)好的。就像我说的,我可以组成一个阵列。之后,我从该阵列下载所有图像。之后,不知何故,我会替换所有旧图像,以获取新图像。我认为这是更现实的。我对吗?
类似的东西:
$ subject =#我会把有文章内容(带有img标签等)
$ result = array();
preg_match(/< img。*?src =(。*?)。*?> /,$ subject,$ result);
foreach($ result as $ src)
{
$ new_src = downloadImage($ src);
#以某种方式将旧图像替换为新图像。怎么样?
}
3)我会用第二种方法吗?
我想你需要 preg_replace_callback ,但请记住 downloadImage
可能会失败。所以优雅地处理失败(后备图像或重试队列)
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?
I think you need preg_replace_callback but keep in mind that downloadImage
may fail. so handle the failure gracefully (a fallback image or a retry queue)
这篇关于正则表达式,解析img src内容并用另一个链接替换它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!