How to remove the first two directories from a file path string?

纵饮孤独 提交于 2020-06-13 09:15:24

问题


I have a string "./product_image/Bollywood/1476813695.jpg".

first I remove . from first.

now I want to remove all character between first two / . that means I want

Bollywood/1476813695.jpg

I am trying with this but not work

substr(strstr(ltrim('./product_image/Bollywood/1476813695.jpg', '.'),"/product_image/"), 1);

It always return product_image/Bollywood/1476813695.jpg


回答1:


Easily done with explode():

$orig = './product_image/Bollywood/1476813695.jpg';
$origArray = explode('/', $orig);
$new = $origArray[2] . '/' . $origArray[3];

result:

Bollywood/1476813695.jpg

If you want something a little different you can use regex with preg_replace()

$pattern = '/\.\/(.*?)\//';
$string = './product_image/Bollywood/1476813695.jpg';
$new = preg_replace($pattern, '', $string);

This returns the same thing and you could, if you wanted, put it all in one line.




回答2:


$str = "./product_image/Bollywood/1476813695.jpg";

$str_array = explode('/', $str);

$size = count($str_array);

$new_string = $str_array[$size - 2] . '/' . $str_array[$size - 1];

echo $new_string;



回答3:


please follow the below code

$newstring = "./product_image/Bollywood/1476813695.jpg";
$pos =substr($newstring, strpos($newstring, '/', 2)+1);
var_dump($pos);

and output will be looking

Bollywood/1476813695.jpg

for strpos function detail please go to below link

http://php.net/manual/en/function.strpos.php

for substr position detail please go to below link

http://php.net/manual/en/function.substr.php



来源:https://stackoverflow.com/questions/40115894/how-to-remove-the-first-two-directories-from-a-file-path-string

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