Removing part of path in php

≡放荡痞女 提交于 2019-12-12 00:09:42

问题


I have a path like:

$path='somefolder/foo/bar/lastdir';

and I want to remove the last part, so I have:

$path='somefolder/foo/bar';

Like I went one folder up.

I'm really newbie in php, maybe its just one function, although I can't find it anywhere.


回答1:


You could try this (tested and works as expected):

$path = 'somefolder/foo/haha/lastone';
$parts = explode('/', $path);
array_pop($parts);
$newpath = implode('/', $parts);

$newpath would now contain somefolder/foo/haha.




回答2:


use :

dirname(dirname('somefolder/foo/haha/lastone/somescript.php'));

this should return:

somefolder/foo/haha/



回答3:


This is untested, but try:

$path_array = explode('/',$path);
array_pop($path_array);
$path = implode('/',$path_array);



回答4:


If you are currently at:

somefolder/foo/haha/lastone/somescript.php

and you want to access:

somefolder/foo/haha/someotherscript.php

just type:

../someotherscript.php



回答5:


Probably using a regex function would be appropriate if the last part is going to vary. Try

$pattern = '#/.*$#U';
$stripped_path = preg_replace($pattern, '', $original_path);

This will strip everything off the original path string starting from the last forward slash.




回答6:


You could use a function that explodes() the $path variable into an array and then array_pop to get rid of the last element.

function path($path) {
    $arrayPath = explode("/", $path);
    $path = array_pop($arrayPath);

    return $path = implode("/", $path);
}



回答7:


The shortest variant in PHP is:

$path = preg_replace('|/[^/]*$|','', $path);

which uses a regular expression.



来源:https://stackoverflow.com/questions/11618318/removing-part-of-path-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!