preg_replace-将所有内容从行尾返回到第二个斜线

问题描述 投票:0回答:4

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

我只需要使用函数/upload/file.png从此字符串返回preg_replace

我的preg_replace("/.*\/(.*)/", '/$1', $fullPath, -1)仅返回/file.png

php regex preg-replace
4个回答
1
投票

为什么不使用直接方法来实现您真正想要的?

稍后应该很容易阅读:

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

输出显然是:

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

0
投票

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

此正则表达式应该起作用-它捕获一个前斜线,然后捕获任意数量的非前斜线,非换行符。重复两次,然后在行尾。

Demo


0
投票

选中此选项可能会对您有所帮助

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

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

这里是demo


0
投票

您要求使用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


0
投票

使用文件系统/路径功能的替代方法(与正则表达式相比,imho更具可读性:]

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.