John Davidson

php - How to remove part of path until a given directory is found?

0 comments
Message:


I have paths that goes like this template:


`/dir1/dir2/dirN/dirNplus1/dirNplus2/`

And for an example to demonstrate this template:


`/var/www/sei/modules/module1/`

I would like to be able to have a function where I could input a full path and a specific directory and get in return only the right part of the path, removing the left part including the directory specified in the parameter.


In the example given, if I would use:


`function('/var/www/sei/modules/module1/', 'sei')`

Then I would like to get the result as:


`/modules/module1/`

Any ideas on how to achieve this?



My Answer:
You can achieve this by using the `explode()` function in PHP to split the path into an array of directories, then finding the index of the specified directory and joining the remaining directories back together.

Here's an example function that does this:

php
function removePathUntilDirectory($path, $directory) {
$directories = explode('/', $path);
$index = array_search($directory, $directories);

if ($index !== false) {
$remainingDirectories = array_slice($directories, $index);
$result = implode('/', $remainingDirectories);
return '/' . $result;
} else {
return $path;
}
}

// Example usage
$path = '/var/www/sei/modules/module1/';
$directory = 'sei';
$result = removePathUntilDirectory($path, $directory);
echo $result; // Output: /modules/module1/


This function will split the path into an array of directories, find the index of the specified directory, slice the array from that index onwards, and then join the remaining directories back together to form the final path.

Rate this post

4 of 5 based on 2875 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us