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.
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; }
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.