Simple PHP Truncate Function

A neat little PHP function to truncate text that is over a certain amount of characters. Just in-case you’re asking “what does truncate mean?”. In the web design/development world, it’s when you limit the characters in a text string and add ellipsis (…) to the end.

The Function

Here’s the PHP truncate function (must be in tags):

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:

<?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);
?>

Which will return:

Its fo rizzle adipiscing i saw beyonces tizzles and my pizzle went crizzle. Sure sapizzle velizzle, the bizzle...

Note: The function must be included on any page that you want to use it on. If using in WordPress, the functions.php file is the perfect location for the function.

Free Graphics, Icons, Tutorials
Free Graphics Free Fitness Vector Icons Graphics PackFree Camping Vector Graphics PackFree Summer Graphics PackFree File Icon PackFree Fast Food Vector GraphicsFree Music Controls Vector Icon Pack
Sharing is caring...
Like & Follow
Share the love, share this page! Facebook Twitter Google Digg Reddit LinkedIn Pinterest Email
Close [X]
The Web Taylor
1000 Lakeside North Harbour Portsmouth, Hampshire PO6 3EN
02392 123358