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

时间:2014-01-27 20:07:01

标签: php html regex image

我需要在我的网站上制作下一个功能:用户编写文章并在其中附加图像,图像通常不存储在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)如果我将使用第二种方法,我究竟可以更换链接?

2 个答案:

答案 0 :(得分:1)

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

}

当属性存在时,您可以使用setAttribute来操纵所有内容。

如果您确定已设置src,则可以使用hasAttribute

答案 1 :(得分:1)

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

相关问题