views:

90

answers:

3

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

+3  A: 

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
Pascal MARTIN
Thanks Pascal have a nice day
streetparade
Thanks :-) You too.
Pascal MARTIN
A: 
$new_string = str_replace($_SERVER['DOCUMENT_ROOT'], '', $string);
$photo = basename($string);

Links:
- http://de.php.net/str_replace
- http://de.php.net/basename

dbemerlin
A: 

.........

echo basename(str_replace($_SERVER['DOCUMENT_ROOT'], '', '/home/bla/test/pic/photo.jpg'));

// output: photo.jpg
Sarfraz