如何用相对路径替换绝对图像 src url?

How to replace absolute image src urls with relative path?

我有几个 html 文件带有 img 标签和绝对图像路径。我想去掉绝对部分,只留下相对路径。

例如。 http://domain1.com/media/uploads/2017/11/image-test-1.jpg https://domain2.org/photos/uploads/2016/08/anotherimage.png

那两个人会变成这样:

images/image-test-1.jpg images/anotherimage.png

我怎样才能做到这一点?

这是我目前拥有的: preg_replace( "@(http[s]*?://[-\w\.]+)(\/\w+\.(png|jpg))@", 'images/', $url ); 它正在将所有内容返回到上传目录,但是,经过一些调整后它根本不起作用...

我的模式将从 http 匹配到 url 中的最后一个 /,并将其替换为 images/

代码:(Demo)

$urls=[
'http://domain1.com/media/uploads/2017/11/image-test-1.jpg',
'https://domain2.org/photos/uploads/2016/08/anotherimage.png'
];

$urls=preg_replace('~https?://(?:[^/]*/)*~','images/',$urls);

var_export($urls);

输出:

array (
  0 => 'images/image-test-1.jpg',
  1 => 'images/anotherimage.png',
)

图案说明:

~            #Pattern delimiter
https?://    #Match http:// or https://
(?:          #Start non-capturing group
    [^/]*    #Match zero or more non-slash characters
    /        #Match slash
)            #End non-capturing group
*            #Match zero or more occurrences of the non-capturing group
~            #Pattern delimiter

这是一个pattern demo。 *注意,我必须将 \s 添加到否定字符 class 以使其匹配一个字符串中的多个 url。


至于你的模式:

@
(              #this generates capture group number 1
    http
    [s]*?      #simpler would be: s?
    ://
    [-\w\.]+   #dot doesn't need escaping; this will match [-A-Za-z0-9_.]
)
(              #this generates capture group number 2
    \/         #escaping is not necessary, just use: /
    \w+        #this will match one or more of [A-Za-z0-9_]
    \.         #this will match literal dot
    (png|jpg)  #this generates capture group number 3 containing png or jpg
)
@

要修复您的模式:(Demo)

  • 添加 /[-\w.] 更改为:[-\w./]
  • 将文件匹配组件从 \w+ 更改为 [\w-]+
  • 将替换更改为:images