我有字符串/fsd/fdstr/rtgd/file/upload/file.png
。
我只需要使用函数/upload/file.png
从此字符串返回preg_replace
。
我的preg_replace("/.*\/(.*)/", '/$1', $fullPath, -1)
仅返回/file.png
。
为什么不使用直接方法来实现您真正想要的?
稍后应该很容易阅读:
<?php
var_dump(
preg_replace('|^.*(/[^/]+/[^/]+)$|', '$1', "/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
使用文件系统/路径功能的替代方法(与正则表达式相比,imho更具可读性:]
$path = '/fsd/fdstr/rtgd/file/upload/file.png';
$folder = dirname($path);
$fileName = basename($path);
$result = '/' . basename($folder) . '/' . $fileName;