
click to enlarge
The PHP code to truncate text but retain its meaning is as follows:
// Original PHP code by Chirp Internet: www.chirp.com.au
function myTruncate($text, $limit, $break=".", $pad="...")
{
if(strlen($text) <= $limit) return $text;
if(false !== ($breakpoint = strpos($text, $break, $limit)))
{
if($breakpoint < strlen($text) - 1)
{ $text = substr($text, 0, $breakpoint) . $pad; }
}
return $text;
}
$text refers to the original text that requires truncation.
$limit refers to the number of characters needed that needs display after the truncation.
$break refers to a character, usually a full stop (.) that indicates where to break the text for truncation.
$pad refers to any suffix for addition to the end of the truncated text, usually (…).
strlen() returns the length of the string ($text in this case).
strpos() returns the position of the first occurrence of a string inside another string ($text in this case).
The code checks and returns the $text unchanged if the length of $text is shorter than the figure indicated in $limit.
The code then checks if the character indicated in $break (.) is present beyond the $limit figure in $text till the end of $text.
If the $break (.) is present beyond $limit and before the end of $text, the truncation happens by default at this point (.).
The following code displays the first 300 characters of $text and continues till the next “.”
$shortdesc = myTruncate($text, 300, " "); echo "<p>$shortdesc</p>";
The following code displays the first 300 characters of $text and continues till the next white space, or the end of the word. This brings the final text length closer to $limit
$shortdesc = myTruncate($description, 300, " "); echo "<p>$shortdesc</p>";