【问题标题】:Get "at most" last n characters from string using PHP substr?使用PHP substr从字符串中获取“最多”最后n个字符?
【发布时间】:2016-05-06 21:53:12
【问题描述】:

这个问题的答案:

如何获取 PHP 字符串的最后 7 个字符? - 堆栈溢出 How can I get the last 7 characters of a PHP string?

显示此语句:

substr($s, -7)

但是,如果 $s 的长度小于 7,它将返回空字符串(在 PHP 5.2.6 上测试),例如

substr("abcd", -4) returns "abcd"
substr("bcd", -4) returns nothing

目前,我的解决方法是

trim(substr("   $s",-4)) // prepend 3 blanks

是否有另一种优雅的方式来编写 substr() 使其更完美?

====

编辑:对不起,我的帖子中 substr("bcd", -4) 的返回值的错字。它误导了这里的人。它不应该返回任何东西。我已经纠正了。 (@2016/1/29 17:03 GMT+8)

【问题讨论】:

  • substr( $s, ( strlen($s) >= 7 ? 7 : strlen($s) ) );?
  • 您希望在上一个示例中得到什么输出?
  • 那么你想要什么输出?
  • 我希望当我想得到最后 4 个字符时,但如果没有足够的字符,整个字符串将被返回,即我在标题中写的“最多”,而不是“完全”。
  • @ScottChu substr("bcd", -4) 返回整个字符串 bcd。什么真的不起作用?

标签: php substr


【解决方案1】:
substr("abcd", -4) returns "abcd"
substr("bcd", -4) returns "bcd"

这是substr() 的正确行为。

PHP 版本 5.2.2-5.2.6 中的 substr() 函数存在一个错误,当其第一个参数 (start) 为负且其绝对值大于长度时,它会返回 FALSE字符串。

行为是documented

您应该将您的 PHP 升级到更新的版本(5.6 或 7.0)。 PHP 5.2 是 5 年多前的 dead and buried

或者,至少,将 PHP 5.2 升级到其最新版本 (5.2.17)


对您的请求的优雅解决方案(假设您被错误的 PHP 版本锁定):

function substr52($string, $start, $length)
{
    $l = strlen($string);
    // Clamp $start and $length to the range [-$l, $l]
    // to circumvent the faulty behaviour in PHP 5.2.2-5.2.6
    $start  = min(max($start, -$l), $l);
    $length = min(max($start, -$l), $l);

    return substr($string, $start, $length);
}

但是,当$length0FALSENULL 或省略时,它不处理。

【讨论】:

    【解决方案2】:

    在我第一次发表评论时,我错过了一个参数 - 我认为它应该更像这样。

    $s = 'look at all the thingymajigs';
    echo trim( substr( $s, ( strlen( $s ) >= 7 ? -7 : -strlen( $s ) ), strlen( $s ) ) );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 2011-12-19
      • 2018-12-03
      相关资源
      最近更新 更多