PHP

PHP Return String From String Using Word Limit Examples

Some times, it might be useful to extract string from a given string, based upon the word count. A good example of this is an excerpt of WordPress. As you know, an “excerpt” is just a sneak peak of the article. And it is limited by it’s word count (or any other desired criteria). So how can we achieve the same result in PHP? In this article, I am going to share easy ways to return text from a given text, based upon the word count limit. So follow along for more info.

How To Limit String Using Word Count

Let’s see how to do this with an example.

Example: Consider the following string on which we apply word limit using PHP

This is a custom string. We are now going to apply PHP functions on this and return only the portion of the string based upon the word count.

Now let’s limit the above string to a word count of 10 and then return the result. Use the following code to do so:

<?php 
function word_limiter($string, $limit) 
{ 
	//break string based upon space
	$str_array = explode(" ", $string); 

	//return the extracted string with our word limit in place
	return implode(" ", array_splice($str_array, 0, $limit)); 
}

$string = 'This is a custom string. We are now going to apply PHP functions on this and return only the portion of the string based upon the word count.';

$word_limit = 10; //Change this based upon your needs

echo word_limiter($string, $word_limit);
?>

 Output:

This is a custom string. We are now going to

If you count the number of word in the above Output, you will notice that there are only 10 words. This is exactly what we wanted.

That’s it!

Do you know of any other ways to limit string using word count in PHP? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*