繁体   English   中英

正则表达式,解析img src内容并用其他链接替换它

[英]Regular expression, parsing img src content and replacing it with another links

我需要在我的网站上制作下一个功能:用户编写文章并在其中附加图像,图像通常不存储在localhost上。 我需要将此图像下载到localhost并替换localhost映像的链接。

例如:

<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 = # i will put there article content (with img tags etc)
$result = array();
preg_match("/<img.*?src="(.*?)".*?>/", $subject, $result);

现在$result数组将包含图像的所有链接。 尼斯。 现在我有一些问题。

1)如果我使用preg_replace ,它会帮助我解决这个任务吗? 在我看来不是,因为preg_replace会立即替换内容(因此我无法下载图像,创建存储在localhost图像上的新链接,并以某种方式将其设置为preg_replace参数,因为它已经运行)。 我对这个假设是对的吗?

2)好的 我可以形成一个数组,就像我说的那样。 之后,我从该阵列下载所有图像。 在那之后,不知何故,我将替换所有旧图像,以换取新图像。 我认为这更现实。 我对吗?

像这样的东西:

$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)如果我将使用第二种方法,我究竟能如何替换链接?

Php DOMDocument示例如何操作HTML图像标记。

$dom=new DOMDocument();
$dom->loadHTML($html_src);
$imgs = $dom->getElementsByTagName('img');
foreach($imgs as $img){

    $img_src = $img->getAttribute('src'); // will give you the src String

    //do something here

    $img->setAttribute('src',$new_src); // change your src= value

}

当Attribute存在时,您可以使用setAttribute操作所有内容。

如果你想确定,设置了src ,那么你可以使用hasAttribute

我认为你需要preg_replace_callback但请记住, downloadImage可能会失败。 所以优雅地处理失败(后备图像或重试队列)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM