There are multiple correct answers here. But it isn't obvious what is needed, if you want a "safe" version of substr
,
Same as substr
, when the string is "long enough", but if the string is too short, return the original string (instead of returning false
).
/** Unlike substr, handles case where $string is too short.
* @param $string
* @param $nChars - negative to return at end of string.
*/
function safe_substr($string, $nChars) {
if ($nChars == 0 || !isset($string))
return "";
if (strlen($string) <= abs($nChars))
// $string is too short (or exactly the desired length). Return the string.
return $string;
return substr($string, $nChars);
}
NOTE: FOR UTF-8 chars, define safe_mb_substr
, replacing substr
above with mb_substr
. And replace strlen
with mb_strlen
.