douxiegan6468 2012-03-27 04:48
浏览 94
已采纳

PHP正则表达式替换图像SRC属性

I'm trying to find a regular expression that would allow me replace the SRC attribute in an image. Here is what I have:

function getURL($matches) {
  global $rootURL;
  return $rootURL . "?type=image&URL=" . base64_encode($matches['1']);
}

$contents = preg_replace_callback("/<img[^>]*src *= *[\"']?([^\"']*)/i", getURL, $contents);

For the most part, this works well, except that anything before the src=" attribute is eliminated when $contents is echoed to the screen. In the end, SRC is updated properly and all of the attributes after the updated image URL are returned to the screen.

I am not interested in using a DOM or XML parsing library, since this is such a small application.

How can I fix the regex so that only the value for SRC is updated?

Thank you for your time!

  • 写回答

2条回答 默认 最新

  • duandi8838 2012-03-27 04:57
    关注

    Do another grouping and prepend it to the return value?

    function getURL($matches) {
      global $rootURL;
      return $matches[1] . $rootURL . "?type=image&URL=" . base64_encode($matches['2']);
    }
    
    $contents = preg_replace_callback("/(<img[^>]*src *= *[\"']?)([^\"']*)/i", getURL, $contents);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?