如果我将以下网址作为字符串:
www.example.com/img/1.png
如何在URL中的最后一个斜杠之后添加字符串extra/
,结果如下:
www.example.com/img/extra/1.png
答案 0 :(得分:2)
echo preg_replace('#(/[^/]+)(?=/[^/]+/?$)#', '$1/extra', $url);
<强>解释强>
( # group and capture to backreference $1
/ # match literal '/'
[^/]+ # any character except: '/' (1 or more times)
) # end of capturing group 1
(?= # look ahead to see if there is: '/'
[^/]+ # any character except: '/' (1 or more times)
/? # '/' (optional)
$ # assert position at the end of string
) # end of look-ahead