[英]Get “at most” last n characters from string using PHP substr?
Answer of this question: 这个问题的答案:
How can I get the last 7 characters of a PHP string? 如何获取PHP字符串的最后7个字符? - Stack Overflow How can I get the last 7 characters of a PHP string? -堆栈溢出如何获取PHP字符串的最后7个字符?
shows this statement: 显示以下语句:
substr($s, -7)
However, if length of $s is smaller than 7, it will return empty string(tested on PHP 5.2.6), eg 但是,如果$ s的长度小于7,它将返回空字符串(在PHP 5.2.6上测试),例如
substr("abcd", -4) returns "abcd"
substr("bcd", -4) returns nothing
Currently, my workaround is 目前,我的解决方法是
trim(substr(" $s",-4)) // prepend 3 blanks
Is there another elegant way to write substr() so it can be more perfect? 还有另一种写substr()的优雅方法,它可以更完美吗?
==== ====
EDIT: Sorry for the typo of return value of substr("bcd", -4) in my post. 编辑:对不起,我的帖子中substr(“ bcd”,-4)返回值的错字。 It misguides people here. 它误导了这里的人们。 It should return nothing. 它应该不返回任何内容。 I already correct it. 我已经纠正了。 (@ 2016/1/29 17:03 GMT+8) (@ 2016/1/29 17:03 GMT + 8)
substr("abcd", -4) returns "abcd"
substr("bcd", -4) returns "bcd"
This is the correct behaviour of substr()
. 这是substr()
的正确行为。
There was a bug in the substr()
function in PHP versions 5.2.2-5.2.6 that made it return FALSE
when its first argument ( start
) was negative and its absolute value was larger than the length of the string. PHP版本5.2.2-5.2.6中的substr()
函数中存在一个错误,当其第一个参数( start
)为负且其绝对值大于字符串的长度时,它返回FALSE
。
The behaviour is documented . 该行为已记录在案 。
You should upgrade your PHP to a newer version (5.6 or 7.0). 您应该将PHP升级到较新的版本(5.6或7.0)。 PHP 5.2 is dead and buried more than 5 years ago. PHP 5.2 已死并被埋葬超过5年。
Or, at least, upgrade PHP 5.2 to its latest release (5.2.17) 或者至少将PHP 5.2升级到最新版本(5.2.17)
An elegant solution to your request (assuming you are locked with a faulty PHP version): 一个完美的解决方案(假设您被错误的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);
}
However, it doesn't handle the cases when $length
is 0
, FALSE
, NULL
or when it is omitted. 但是,它不能处理$length
为0
, FALSE
, NULL
或省略时的情况。
In my haste with first comment I missed a parameter - I think it should have been more like this. 急于我的第一条评论,我错过了一个参数-我认为它应该更像这样。
$s = 'look at all the thingymajigs';
echo trim( substr( $s, ( strlen( $s ) >= 7 ? -7 : -strlen( $s ) ), strlen( $s ) ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.