php中从html中提取图片路径,并且替换的方法

思路是这样:

先用正则表达式获取IMG标签,然后把每个IMG标签的SRC抽取出来,并且组合成自己的内容,最后进行替换。

 

例子如下所示:

 

//要替换的内容    
    $content = '<img alt="" src="js/fckeditor/UserFiles/image/F201005201210502415831196.jpg" width="600" height="366"><br><br><br><br><img alt="" src="js/fckeditor/UserFiles/image/33_avatar_middle.jpg" width="120" height="120">';

    //提取图片路径的src的正则表达式
    preg_match_all("/<img(.*)src=\"([^\"]+)\"[^>]+>/isU",$content,$matches);

            $img = "";
            if(!empty($matches)) {
            //注意,上面的正则表达式说明src的值是放在数组的第三个中
                $img = $matches[2];
            }else {
                $img = "";
            }
            if (!empty($img)) {
                $img_url = "http://".$_SERVER['SERVER_NAME'];

                $patterns= array();
                $replacements = array();

                foreach($img as $imgItem){

                $final_imgUrl = $img_url.$imgItem;
                $replacements[] = $final_imgUrl;

                $img_new = "/".preg_replace("/\//i","\/",$imgItem)."/";
                $patterns[] = $img_new;

                }

                //让数组按照key来排序
                ksort($patterns);
                ksort($replacements);

                //替换内容
                $vote_content = preg_replace($patterns, $replacements, $content);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值