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

时间:2018-02-17 05:09:47

标签: php regex preg-replace

我有几个带有img标签和绝对图像路径的html文件。我想删除绝对部分,然后留下相对路径。

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

这两个人最终会这样:

图像/图像测试1.JPG 图像/ anotherimage.png

我该如何做到这一点?

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

1 个答案:

答案 0 :(得分:2)

我的模式将匹配从http到网址中的最后一个/,并将其替换为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添加到否定的字符类中,以使其与一个字符串中的多个网址匹配。

至于你的模式:

@
(              #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$2
相关问题