Word Limiting With Regular Expressions
Here’s my take on limiting words in a paragraph.
^s*((?:S+s*){0,20})(.*)
That’ll capture the first 20 words and also the rest of the string. Then, you can replace the entire capture with the first capture group (the first 20 words). In PHP:
function ak_limit_words($str, $word_limit) { return preg_replace('#^s*((?:S+s*){0,'.$word_limit.'})(.*)#msi', '$1', $str); } // Output: 'this is the ' ak_limit_words('this is the sentence...', 3);