3

I have a variable like $path = "dir1/dir2/dir1/dir4/"; etc.. etc..

I want to remove the first member dir1/ and want result like dir2/dir1/dir4/.

I think it is possible by making the variable an array by explode('/', $path). How can I remove the first member vrom array and reconstruct that array into a text variable??

How can I achieve this in PHP?

4 Answers 4

8

According to your updated question

Only explode into two parts, take the second one. In case the second one does not exists, give it NULL:

list(, $result) = explode("/", $path, 2) + array( 1 => NULL);

OR

$array = explode("/", $path);
unset($array[0]);
echo $text = implode("/", $array);
Sign up to request clarification or add additional context in comments.

7 Comments

@blasteralfred why did you choose 3 lines over one simple line with regexp?
@meze: regexp are slow than these functions and you can also convert these three lines in one line of code
how do you know that regexp is slower than these lines? Regexp isn't always slow. In some cases regexp will be faster than those three lines. And you can't convert it into one line of code.
It's not "these three lines" anymore, it's different now ;) And it became slower than the regexp solution because internally it will create 2 arrays...
@meze: And do you know what preg_replace internally does? It is not recommended to use regex until you really need it.
|
5
preg_replace('~^[^/]+/~', '', $path);

or if you don't want regexp:

substr($path, strpos($path, '/') + 1);

1 Comment

This answer is missing its educational explanation. Not all researchers understand regex pattern syntax. There should probably be a warning in this answer regarding the fact that you are not checking strpos() for === false, and any passed in string without slashes will have unintended mutation.
1
$result = explode("/", $path); // Pull it apart
array_shift($result); // Pop the first index off array
$result = implode("/", $result); // Put it together again

Comments

0

You can do like that $result= explode("/", $path);. You will get result as an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.