PHP Regex Replace Image SRC Attribute

▼魔方 西西 提交于 2019-12-11 05:25:26

问题


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!


回答1:


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);



回答2:


Use a lazy star instead of a greedy one.

This may be your problem:

/<img[^>]*src *= *[\"']?([^\"']*)/
         ^

Change it to:

/<img[^>]*?src *= *[\"']?([^\"']*)/

This way, the [^>]* matches the smallest possible number of your bracket expression, rather than the largest possible.



来源:https://stackoverflow.com/questions/9883517/php-regex-replace-image-src-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!