Get "at most" last n characters from string using PHP substr? -


answer of question:

how can last 7 characters of php string? - stack overflow how can last 7 characters of php string?

shows statement:

substr($s, -7) 

however, if length of $s smaller 7, return empty string(tested on php 5.2.6), e.g.

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

currently, workaround is

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

is there elegant way write substr() can more perfect?

====

edit: sorry typo of return value of substr("bcd", -4) in post. misguides people here. should return nothing. correct it. (@ 2016/1/29 17:03 gmt+8)

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

this correct behaviour of substr().

there bug in substr() function in php versions 5.2.2-5.2.6 made return false when first argument (start) negative , absolute value larger length of string.

the behaviour documented.

you should upgrade php newer version (5.6 or 7.0). php 5.2 dead , buried more 5 years ago.

or, @ least, upgrade php 5.2 latest release (5.2.17)


an elegant solution request (assuming locked faulty php version):

function substr52($string, $start, $length) {     $l = strlen($string);     // clamp $start , $length range [-$l, $l]     // circumvent 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, doesn't handle cases when $length 0, false, null or when omitted.


Comments