【问题标题】:PHP string : remove last item after slashPHP字符串:删除斜线后的最后一项
【发布时间】:2014-08-20 12:05:37
【问题描述】:

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

$string = '/me/you/them/him';

echo substr($string, 0, -(strlen(basename($string)) + 1));

【问题讨论】:

  • 你如何定义一个更好的方式?
  • dirname 将适用于该确切样本。
  • 我会用 / 分解字符串,然后重新构建没有最后一个的字符串。
  • 也许更多efficient - 是一个无需调用这么多单独函数就可以做类似事情的函数吗?
  • 对于更一般的情况(任何分隔符),implode('/', array_slice(explode('/', $string), 0, -1)

标签: php string substring


【解决方案1】:

dirname 函数呢?

$output = dirname($string);

输出:

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

【讨论】:

  • 离我还有 6 分钟的路程
【解决方案2】:

由于不清楚更好的方法对您意味着什么,我想到了一种替代方法:

$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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2015-01-12
    相关资源
    最近更新 更多