PHP返回路径的一部分

时间:2018-09-21 16:58:10

标签: php

我有一条这样的路径:

df1 <- structure(list(symbol = c("MSFT", "5563.T", "WB", "0992.HK", 
"005930.KS"), year = c(2017L, 2017L, 2017L, 2017L, 2017L), adjusted = c(101.459557, 
307, 90.970001, 3.945, 45600), Total.Revenue = c(9.6571e+10, 
7.1346e+10, 1150054000, 43034731000, 2.3958e+14)), .Names = c("symbol", 
"year", "adjusted", "Total.Revenue"), row.names = c(NA, -5L), class = c("tbl_df", 
"tbl", "data.frame"))

如何将最后两个目录和文件名作为单个字符串返回? 我希望返回“ general / banners / header3.jpg”。请记住,目录和文件名可能会有所不同。

谢谢! 里克

3 个答案:

答案 0 :(得分:1)

$string = '../../images/trades/general/banners/header3.jpg';
echo lastPortionOfPath($string);

function lastPortionOfPath($string, $segments= 3) {
    $chunks = explode('/', $string);
    $chunks = array_slice($chunks, count($chunks) - $segments, $segments);

    return implode('/', $chunks);
}

答案 1 :(得分:1)

$chain = "../../images/trades/general/banners/header3.jpg";
/*
*  All this regex do the same thing
*
$regex = "/^.+(\/[a-zA-Z0-9]+\/[a-zA-Z0-9]+\/[a-zA-Z0-9]+\.[a-zA-Z]+)$/";
$regex = "/^.+((\/[a-zA-Z0-9]+){3}\/[a-zA-Z0-9]+\.[a-zA-Z]+)$/";
$regex = "/^.+((\/[a-zA-Z0-9]+){3}\.[a-zA-Z]+)$/";
*/

创建符合您需要的正则表达式字符串

$regex = "/^.+((\/[a-zA-Z0-9]+){3}\.[a-zA-Z]{2,})$/";

括号用于捕获括号中与正则表达式匹配的所有内容,并且可以使用preg_match函数的第三个值(在这种情况下为$matches

)来检索所有值。
if(preg_match( $regex, $chain, $matches)){
    // $result will be equal to "/general/banners/header3.jpg"
    $result = substr($matches[1], 1, strlen($matches[1]) - 1); // remove the first /
}
echo $result; // general/banners/header3.jpg

答案 2 :(得分:0)

逐步:

路径

$path = "../../images/trades/general/banners/header3.jpg";

用斜杠分隔字符串

$path = explode('/',$path);   

读取生成的数组的大小并减去3,因为这是您想要的部分数(1个文件+ 2个目录):

$pathSize=count($path)-3;
$newPath = $path[$pathSize].'/'.$path[$pathSize+1].'/'.$path[$[pathSize+2];

显示结果

echo 'Result: '.$newPath;