You can use:
substr ($getstring->string, -4)
Because of (-) it will start form the end of the string and it will take the next 4 characters.
Take care that first() it will return an object and not the string you want.
Answer from Radu on Stack OverflowYou can use:
substr ($getstring->string, -4)
Because of (-) it will start form the end of the string and it will take the next 4 characters.
Take care that first() it will return an object and not the string you want.
Please read the manual substr.
$str = substr($str, -4);
Use substr() with a negative number for the 2nd argument.
$newstring = substr($dynamicstring, -7);
From the php docs:
string substr ( string $string , int $start [, int $length ] )If start is negative, the returned string will start at the start'th character from the end of string.
umh.. like that?
$newstring = substr($dynamicstring, -7);
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.
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 ) ) );