PHP字符串:删除斜杠后的最后一项


PHP string : remove last item after slash

是否有更好的方法来删除最后一个斜杠(包括斜杠)之后的子字符串?:

$string = '/me/you/them/him';
echo substr($string, 0, -(strlen(basename($string)) + 1));

dirname函数呢?

$output = dirname($string);
输出:

string '/me/you/them' (length=12)

由于不清楚更好的方法对您来说意味着什么,这里是我想到的另一种方法:

$str = '/me/you/them/him';
// Split $str on '/' char into an array
$pieces = explode('/', $str);
// Glue the pieces back together, excluding the last item
$str = implode('/', array_slice($pieces, 0, -1));
echo $str; // '/me/you/them'