Expert Group of programming

Truncating strings using PHP

Posted by : Heycode Tech | Posted in : php, WordPress Functions | Jan 30,2016 | 0 comments

When we are displaying the text in webpage, then a common problem occurs for text is too long or Text have cut from last word. As we know that it is a very serious problem also .


For solution of this problem is to TRANCATE the text But we need a function which is used for truncate the string. Now here I ‘ll explains it as well as provide the functions also.

1:Truncating Text by Char and return word

Now this below function will truncate the string in works. Now suppose you need the 100 character then it will check that all the 100 character are in full words if yes then it will return but if all the 100 character are not in full word i.e last work has incomplete then it will leave the last word and return the only complete word.

1: Limited to 20 chars:

Lorem ipsum dolor sit amet

Output : Lorem ipsum doller

1: Limited to 21 chars :
Output : Lorem ipsum doller

Now when you will increase the character then it will first check it it will receive any complete word then it will accept in output otherwise leave it and return only completed word.


function heycode_get_word_count($string,$limit=250){
 	$allchars = $string;
 //$string = strip_tags($allchars); //Enable this comment, if you disable all HTML tag and count only content.
	$string = substr($string,0,$limit);
     $string = substr($string,0,strrpos($string," "));
     return $string;
//How to call
$string = "Lorem ipsum doller sit amit";
echo heycode_get_word_count($string,21);

2:Truncating Text by word and return word

If you simply want to truncate text to a certain number of words then this function is used for that.It will truncate the full word.

Limited to 9 words:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque
1 2 3 4 5 6 7 8 9

Here is the function :

function heycode_get_word($string,$numwords){
  preg_match("/(\S+\s*){0,$numwords}/", $string, $regs);
  $wordCount = trim($regs[0]);
  return $wordCount;
//how to use
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque Lorem ipsum doller";
echo heycode_get_word($string,9);

Please Note: This function is experimental so please use it and still any problem then share with me. I will very pleasure to see the response.

Thanks for support and spending the time.


Author information - Heycode Tech

Every world can ask question and my website registered user give the suggestion.

See all posts by Author

Connect to author

Leave a Reply

Your email address will not be published. Required fields are marked *

About us

Heycodetech is a platform where you can ask any questions related to the programming like PHP,jQuery, MYSQL,HTML , CSS and more Here is the Expert group of programming.