Enquiry Email Form

Here’s a quick function that will limit the amount of words that will display from a string of words, so you effectively get a excerpt/teaser. For example, let’s assume you have the following sentence:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit buyessaysonlinecheap.net in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Let’s assume you only want to show the first 10 words, like the following:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do

PHP- Show Excerpt/Tease From Sentence function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function string_excerpt($string, $count){
 $words = explode(' ', $string);
 if (count($words) > $count)
 {
  $words = array_slice($words, 0, $count);
  $string = implode(' ', $words);
 }
 return $string;
}
 
//the string we want to create an excerpt/teaser for
$string = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
 
//The amount of words we want to show
$count = 10;
 
echo string_excerpt($string, $count);

Note

A word is defined by a character or letters that has a space on neither side of it, so the following will also get counted as one word ” – ”

If you want to limit the amount of characters to show (as opposed to “words”), refer to the substr function.

Learning & sharing

This is where we store some of our Web Development thoughts, tips and tricks for both our own uses and for others to learn from. Sharing is caring.

Please feel free to contribute to our blog posts; perhaps even teach us a few tricks of your own. We'd love to hear your thoughts.



X