[php] Truncating Text in PHP?

I'm trying to truncate some text in PHP and have stumbled across this method (http://theodin.co.uk/blog/development/truncate-text-in-php-the-easy-way.html), which judging by the comments seems like a great easy-to-implement solution. The problem is I don't know how to implement it :S.

Would someone mind pointing me in the direction of what to do to implement this? Any help whatsoever would be appreciated.

Thanks in advance.

This question is related to php truncate

The answer is


$text="abc1234567890";

// truncate to 4 chars

echo substr(str_pad($text,4),0,4);

This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)


$mystring = "this is the text I would like to truncate";

// Pass your variable to the function
$mystring = truncate($mystring);

// Truncated tring printed out;
echo $mystring;

//truncate text function
public function truncate($text) {

    //specify number fo characters to shorten by
    $chars = 25;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}