note 78019 deleted from function.substr by cmb
| From: | cmb@php.net | Date: | Sun, 27 Oct 2019 09:09:21 +0000 |
| Subject: | note 78019 deleted from function.substr by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212828@lists.php.net to get a copy of this message | ||
Note Submitter: morgangalpin att gmail dotty com
----
Adding the $limit parameter introduced a bug that was not present in the original. If $limit is
small or negative, a string with a length exceeding the limit can be returned. The $limit parameter
should be checked. It takes slightly more processing, but it is dwarfed in comparison to the use of
strlen().
<?php
function short_name($str, $limit)
{
// Make sure a small or negative limit doesn't cause a negative length for substr().
if ($limit < 3)
{
$limit = 3;
}
// Now truncate the string if it is over the limit.
if (strlen($str) > $limit)
{
return substr($str, 0, $limit - 3) . '...';
}
else
{
return $str;
}
}
?>