drfu29983 2014-01-27 20:07
浏览 82

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

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?

  • 写回答

2条回答 默认 最新

  • duanjia7607 2014-01-28 07:32
    关注

    A Php DOMDocument Example how to manipulate HTML image tags.

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

    You can manipulate everything with setAttribute when the Attribute exist.

    If you want be sure, that src is set, then you can use hasAttribute

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向