hi guys i want to extract the first 50 word from a text.. is there any php function which will let me do that?? thanks in advance..
I think this regex will do the trick $numwords = 50; preg_match("/(\S+\s+){0,$numwords}/", $long_string, $regs); $short_string = trim($regs[0]); PHP:
Try this: preg_match('#((?:\S+\s+){50})#', $string, $matches); echo $matches[1]; PHP: This is similar to the above but the actual index in the array is 1 not 0. Also you the above regex will match the first word only...
Why do we need regex, won't $text = substr($text, 0, 50); PHP: Do the trick?? Where $text is the text you want to trim to 50 characters. You can save it in a new variable, that one just overwrites $text.
That would work if you want to get the first 50 Characters but he was asking for the first 50 words. In which case it's best to use a regex that counts the first 50 words. See http://www.the-art-of-web.com/php/truncate/ for more methods of truncating text.