preg_replace - return 从行尾开始到第二个斜杠的所有内容

preg_replace - return everything to the second slash from the end of the line

我有字符串 /fsd/fdstr/rtgd/file/upload/file.png.

我只需要 return 来自这个字符串 /upload/file.png 使用函数 preg_replace.

我的 preg_replace("/.*\/(.*)/", '/', $fullPath, -1) return 只有 /file.png.

((?:\/[^\/\n]*){2})$

这个正则表达式应该可以工作 - 它捕获一个前斜杠,然后是任意数量的非前斜杠、非换行符文本。这重复两次,然后是行尾。

Demo

检查这个可能对你有帮助

(\/\w+\/\w+\.\w{3,4})$

我们在正则表达式的末尾添加 $ 以从末尾而不是开头验证

这是一个demo

为什么不使用直接方法并实现您实际需要的东西呢?

这以后应该很容易阅读:

<?php
var_dump(
  preg_replace('|^.*(/[^/]+/[^/]+)$|', '', "/fsd/fdstr/rtgd/file/upload/file.png", -1)
);

输出显然是:

string(16) "/upload/file.png"

您要求 preg_replace 解决方案,但也可以通过不同的方式解决:

$string = '/fsd/fdstr/rtgd/file/upload/file.png';

使用数组函数:将字符串分解为数组,然后提取最后两项,然后将它们粘合在一起。

print '/' . implode('/', array_slice(explode('/', $string), -2));

或字符串函数:找到倒数第二个出现的 / 然后提取所有字符直到结束。

print substr($string, strrpos(substr($string, 0, strrpos($string, '/')), '/'));

两者都给出了结果:/upload/file.png

使用 filesystem/path 函数的替代方法(恕我直言,感觉比正则表达式更具可读性):

$path = '/fsd/fdstr/rtgd/file/upload/file.png';

$folder = dirname($path);
$fileName = basename($path);

$result = '/' . basename($folder) . '/' . $fileName;

演示:https://3v4l.org/YblcW