Introduction
Very often we want to display only a chunk of the large text present in database in the front end. For this, we generally split the words to a certain number of characters and display them.
For ex- , if we want to display only 15 characters in the front end and we have a text as "Hello World, This is a very long line of text that needs to be truncated to 15 characters!!", we will take the 1st 15 characters of the text and display the same. This would give an output as "Hello World, Thi". Obviously, this look pretty ugly and not much user-friendly for the users visiting any site.
This tip is helpful to resolve similar kind of situation. Users can use the below function when they need to truncate a long text to a certain number of characters without breaking the word in between.
Using the code
Define the below function in the file you want to use it. In case you want it to use in multiple files, you can always define it one of your core-level files that is included in each file you want this to be used.
function truncate_str($str, $maxlen) {
if (strlen($str) <= $maxlen) {
return $str;
}
$newstr = substr($str, 0, $maxlen);
if ( substr($newstr,-1,1) != ' ' )
$newstr = substr($newstr, 0, strrpos($newstr, " "));
return $newstr;
}
This function requires two parameters:
- Original text to be truncated
- Maximum number of characters the text should be truncated to.
Calling the truncate_str()
function as below will give you the output as "Hello World, " -- thus displaying neat texts without displaying half words.
echo truncate_str("Hello World, This is a very long line of text that will
be truncated to less than 15 characters without breaking the words in between!!", 15);
Hope this little tip helps you!