How can i remove $_SERVER['DOCUMENT_ROOT']
from a string like this
/home/bla/test/pic/photo.jpg
the result should look like this /test/pic/photo.jpg
I also need to take the photo.jpg from /test/pic/photo.jpg
How can i do that i PHP? Thank
How can i remove $_SERVER['DOCUMENT_ROOT']
from a string like this
/home/bla/test/pic/photo.jpg
the result should look like this /test/pic/photo.jpg
I also need to take the photo.jpg from /test/pic/photo.jpg
How can i do that i PHP? Thank
If your DocumentRoot corresponds to the portion of the string you want to remove, a solution could be to use str_replace
:
echo str_replace($_SERVER['DOCUMENT_ROOT'], '', '/home/bla/test/pic/photo.jpg');
But note that you'll run into troubles in the content of $_SERVER['DOCUMENT_ROOT']
is present somewhere else in your string : it will be removed, each time.
If you want to make sure it's only removed from the beginning of the string, a solution could be to use some regex :
$docroot = '/home/bla';
$path = '/home/bla/test/pic/photo.jpg';
echo preg_replace('/^' . preg_quote($docroot, '/') . '/', '', $path);
Note the ^
at the beginning of the regex (to indicate that it should only match at the beginning of the string) -- and don't forget to escape the special characters from your document root, using preg_quote
.
And to get the name of a file when you have a path containing directory + name, you can use the basename
function ; for instance, this portion of code :
echo basename('/test/pic/photo.jpg');
Will give you this output :
photo.jpg
$new_string = str_replace($_SERVER['DOCUMENT_ROOT'], '', $string);
$photo = basename($string);
Links:
- http://de.php.net/str_replace
- http://de.php.net/basename
.........
echo basename(str_replace($_SERVER['DOCUMENT_ROOT'], '', '/home/bla/test/pic/photo.jpg'));
// output: photo.jpg