vitalis emanuel
vitalis emanuel

Reputation: 23

how to remove the first part of a path in php?

i have a path like this:

/dude/stuff/lol/bruh.jpg

i want to echo it like this:

/stuff/lol/bruh.jpg

how to do this? and if you could please explain it. i found one good answer Removing part of path in php but i cannot work my way around with explode and implode.

please give me the link to the duplicate answer if my question is a duplicate

Upvotes: 1

Views: 5945

Answers (4)

Ismael Moral
Ismael Moral

Reputation: 732

You can use a regular expression to extract resource name you need.

preg_match('/(?P<name>[^\/]+)$/', $path, $match);

Then you have to use $match as array, and you can see the name inside of it.

$match['name];

Upvotes: 0

Sanjiv Dhakal
Sanjiv Dhakal

Reputation: 316

Try this :

$string = "/dude/stuff/lol/bruh.jpg";
$firstslash = strpos($string,"/",1);
$secondstring = substr($string, $firstslash+1);
echo "String : " . $string;
echo " <br> Result : " . $secondstring;

Upvotes: 0

Chin Leung
Chin Leung

Reputation: 14921

You could use strpos with substr:

$string = '/dude/stuff/lol/bruh.jpg';
$string = substr($string, strpos($string, '/', 1));

The strpos to look for the position of the / after the first one, then use substr to get the string starting from that position till the end.

Upvotes: 3

Enstage
Enstage

Reputation: 2126

$path = '/dude/stuff/lol/bruh.jpg';
$path = explode('/', $path);
unset($path[1]);
$path = implode('/', $path);

Will separate the string into an array, then unset the first item (technically the second in the array, since the first element will be empty due to the string starting with /). Finally the path is imploded, and you get:

/stuff/lol/bruh.jpg

Upvotes: 2

Related Questions