extract part of a path with filename with php

岁酱吖の 提交于 2021-02-05 10:46:05

问题


I need to extract a portion of urls using php. The last 6 segments of the url are the part I need. The first part of the url varies in length and number of directories. So if I have a url like this:

https://www.random.ccc/random2/part1/part2/part3/2017/08/file.txt

or this:

https://www.random.vov/part1/part2/part3/2016/08/file.pdf

What I need is this:

/part1/part2/part3/2017/08/file.txt

or this:

/part1/part2/part3/2016/08/file.pdf

I have tried this:

$string = implode("/",array_slice(explode("/",$string,8),6,4));

which works ok on the first example but not the second. I am not so good with regex and I suppose that is the way. What is the most graceful solution?


回答1:


Your approach is fine, though adding parse_url in there to isolate just the path will help a lot:

$path  = parse_url($url, PHP_URL_PATH); // just the path part of the URL
$parts = explode('/', $path);           // all the components
$parts = array_slice($parts, -6);       // the last six
$path  = implode('/', $parts);          // back together as a string

Try it online at 3v4l.org.

Now, to qualify: if you only need the string part of the path, then use parse_url. If, however, you need to work with each of the segments (such as removing only the last six, as asked), then use the common pattern of explode/manipulate/implode.

I have left each of these steps separate in the above so you can debug and choose the parts that work best for you.




回答2:


Use this, substituting $url as you wish:

$url= "https://www.random.vov/part1/part2/part3/2016/08/file.pdf";
preg_match("%/[^/]*?/[^/]*?/[^/]*?/[^/]*?/[^/]*?/[^/]*?$%", $url, $matches);
echo $matches[0];

best regards!



来源:https://stackoverflow.com/questions/45807459/extract-part-of-a-path-with-filename-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!