Kinty1931
Kinty1931

Reputation: 11

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

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

Upvotes: 0

Views: 563

Answers (3)

Akbor
Akbor

Reputation: 1348

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

Upvotes: 1

Jay Blanchard
Jay Blanchard

Reputation: 34406

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.

Upvotes: 4

Chris
Chris

Reputation: 486

$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;

Upvotes: 2

Related Questions