Reputation: 990
Answer of this question:
How can I get the last 7 characters of a PHP string? - Stack Overflow How can I get the last 7 characters of a PHP string?
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), e.g.
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?
====
EDIT: Sorry for the typo of return value of substr("bcd", -4) in my post. It misguides people here. It should return nothing. I already correct it. (@ 2016/1/29 17:03 GMT+8)
Upvotes: 2
Views: 871
Reputation: 72256
substr("abcd", -4) returns "abcd"
substr("bcd", -4) returns "bcd"
This is the correct behaviour of 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.
The behaviour is documented.
You should upgrade your PHP to a newer version (5.6 or 7.0). PHP 5.2 is dead and buried more than 5 years ago.
Or, at least, upgrade PHP 5.2 to its latest release (5.2.17)
An elegant solution to your request (assuming you are locked with a faulty PHP version):
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.
Upvotes: 2
Reputation: 33813
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 ) ) );
Upvotes: 0