Trim long texts by words in PHP
We don’t like reading chopped sentences like “Star Wars Old Republic is be….”. It looks fugly. Usually, when trimming text you will go with substr(), but there is a much better way to do it, and believe me, you trimmed text will look so much better than before.
Let’s get to the point. A PHP function that will do the job for us:
function trim_text($input, $length, $ellipses = true, $strip_html = true, $output_entities = true){ // Strip tags, if desired if($strip_html) { $input = strip_tags($input); } // No need to trim, already shorter than trim length if(strlen($input) <= $length) { return $input; } // Find last space within length $last_space = strrpos(substr($input, 0, $length), ' '); $trimmed_text = substr($input, 0, $last_space); // Add ellipses (...) if($ellipses){ $trimmed_text .= '...'; } if($output_entities){ $trimmed_text = htmlentities($trimmed_text); } return $trimmed_text; }
If you need to trim a long text by 120 characters, you could do something like:
echo trim_text($long_text, 120);
The other options are pretty self explanatory. Add elipses (…), remove HTML tags, and return the text with html entities.