开发者

How to remove $_SERVER['DOCUMENT_ROOT'] from a given string in PHP

开发者 https://www.devze.com 2022-12-21 15:57 出处:网络
How can i remove $_SERVER[\'DOCUMENT_ROOT\'] from a string like this /home/bla/test/pic/photo.jpg the result should开发者_运维技巧 look like this

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消