$string
is the string to truncate, $repl
specifies what to replace it with and $limit
is how many characters to allow. If $limit
is greater than the string length then the string is unchanged.
Example usage:
$string = "This is a very long test string that I am using to test long strings";
echo add3dots($string, "...", 12); // Result: "This is a ve..."
The function:
function add3dots($string, $repl, $limit)
{
if(strlen($string) > $limit)
{
return substr($string, 0, $limit) . $repl;
}
else
{
return $string;
}
}
thanks for the script! i recently solved this issue on client side by using the js library cuttr.js to truncate a string and adding the three dots - https://github.com/d-e-v-s-k/cuttr-js
This is a good shortcut !
However, as you mentioned in your example this method actually cut a sentance in the middle of the word "very".
I actually tried to look for solution in order to avoid this issue and found this article that describes how to proceed : https://yoroshikune.com/cut-string-length/
It seems impossible to avoid this problem without building a kind of custom substring function.
Better shortcut
mb_strimwidth("Hello World", 0, 10, "...");
A handy shortcut:
print (strlen($string) > 24)? substr($string, 0, 24) . "...": $string;