How to Add Three Dots to a Long String with PHPHere is a simple little function in PHP that will truncate a string after X number of characters and add three dots or whatever you specify.
Ellipsis are a series of three dots that indicate an intentional omission of a word, sentence or whole section from the original text being quoted. Here is a simple little function in PHP that will truncate a string after X number of characters and replace it with three dots (or whatever you specify). This is useful when showing an excerpt or a short introduction.
$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;
}
}