PHP 正则表达式替换图像 SRC 属性 [英] PHP Regex Replace Image SRC Attribute
问题描述
我试图找到一个正则表达式,它可以让我替换图像中的 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);
在大多数情况下,这很有效,除了当 $contents 回显到屏幕时 src="
属性之前的任何内容都会被消除.最后,SRC
正确更新,更新后的图像 URL 后的所有属性都会返回到屏幕.
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.
我对使用 DOM 或 XML 解析库不感兴趣,因为这是一个很小的应用程序.
I am not interested in using a DOM or XML parsing library, since this is such a small application.
如何修复正则表达式以便仅更新 SRC
的值?
How can I fix the regex so that only the value for SRC
is updated?
感谢您的宝贵时间!
推荐答案
再进行一次分组并将其添加到返回值之前?
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);
这篇关于PHP 正则表达式替换图像 SRC 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!