PHP Truncate function (shorten sentences in length) — Dec 23, 2013, 9:44 am
Since I'll always need this function again, I decided to write it down. There is a nice approach on Stack Overflow, that unfortunately has it's problems.function truncate($text, $chars = 25) { $text = $text." "; $text = substr($text,0,$chars); $text = substr($text,0,strrpos($text,' ')); $text = $text."..."; return $text; }
1. It always runs every input through the functions, no matter if necessary or not.
2. It always sets dots behind a sentence, no matter how short it is.
My simple addition with an if-statement:
function truncate($text, $chars = 25) { if (strlen($text) > $chars) { // leave me alone if I'm short enough $text = $text.' '; $text = substr($text, 0, $chars); $text = substr($text, 0, strrpos($text, ' ')); $text = $text.'...'; } return $text; }