Click here to Skip to main content
15,891,607 members
Articles / Programming Languages / PHP
Tip/Trick

Truncate to max characters without breaking word in between

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
19 Dec 2012CPOL1 min read 12.3K   3  
A handy method to truncate words to a certain number of characters without breaking any word in between

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.  

PHP
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:

  1. Original text to be truncated
  2. 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.

PHP
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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Rebin Infotech
India India
A passionate developer with over 10 years of experience and building my software company code by code. Experience withMS Technologies like .Net | MVC | Xamarin | Sharepoint | MS Project Server and PhP along with open source CMS Systems like Wordpress/DotNetNuke etc.

Love to debug problems and solve them. I love writing articles on my website in my spare time. Please visit my Website for more details and subscribe to get technology related tips/tricks. #SOreadytohelp

Comments and Discussions

 
-- There are no messages in this forum --