在斜杠之前添加一个字符串

时间:2014-03-29 05:12:21

标签: php url

如果我将以下网址作为字符串:

www.example.com/img/1.png

如何在URL中的最后一个斜杠之后添加字符串extra/,结果如下:

www.example.com/img/extra/1.png

1 个答案:

答案 0 :(得分:2)

使用preg_replace()

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

Regex101 Demo

相关问题