Select Page
The Function
Here’s the PHP truncate function (must be in tags):

1
2
3
4
5
6
7
8
9
function truncate($text, $chars = 120) {
    if(strlen($text) > $chars) {
        $text = $text.' ';
        $text = substr($text, 0, $chars);
        $text = substr($text, 0, strrpos($text ,' '));
        $text = $text.'...';
    }
    return $text;
}
Usage
Using the function is simple. To truncate your text just do the following:

1
2
3
4
5
6
7
8
9
10
<?php
// The text string you want to shorten
$string = 'Its fo rizzle adipiscing i saw beyonces tizzles and my pizzle went crizzle. Sure sapizzle velizzle, the bizzle volutpizzle, i saw beyonces tizzles and my pizzle went crizzle my shizz, for sure vizzle, doggy.';
 
// The truncated text to the default 120 characters
echo truncate($string);
 
// The truncated text to 200 characters
echo truncate($string, 200);
?>