Extract a number of words from text

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
CoursesWeb
Forum Newbie
Posts: 18
Joined: Mon Dec 09, 2013 10:52 am

Extract a number of words from text

Post by CoursesWeb »

Hi
This is m 1st post on this forum, and i want to begin with something useful to contribute.
Here is a small php code that can be used to extract a number of words from text.

Code: Select all

$text = 'Extract the text with first 45 characters from this string.';
$nrw = 10;                         // the number of words we want to extract

$rgxwords = '/([^ ]*[ ]{0,1}){1,'.$nrw.'}/i';            // patern to get a number of words from string
$text = preg_replace('/\s\s+/', ' ', $text);             // replace multiple whitespaces whith single space
$text = trim($text);                                     // to remove whitespace from the beginning and ending

// get the substring
if(preg_match($rgxwords, $text, $mtc)) $txt = $mtc[0];
else $txt = '';

echo $txt;
 
Last edited by requinix on Mon Dec 09, 2013 12:54 pm, edited 1 time in total.
Reason: removing advertising
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Extract a number of words from text

Post by Weirdan »

Code: Select all

$text = 'Extract the text with first 45 characters from this string.';
$nrw = 6;

echo join(" ", array_slice(str_word_count($text, 1, '0..9'), 0, $nrw));
CoursesWeb
Forum Newbie
Posts: 18
Joined: Mon Dec 09, 2013 10:52 am

Re: Extract a number of words from text

Post by CoursesWeb »

But if you have comma, dot or other punctuations in text, using array_slice() will lose the punctuations.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Extract a number of words from text

Post by Weirdan »

It depends on what is actually needed. As the title goes, punctuation does not belong to 'words'
CoursesWeb
Forum Newbie
Posts: 18
Joined: Mon Dec 09, 2013 10:52 am

Re: Extract a number of words from text

Post by CoursesWeb »

Yes, You are right. I wrote that code to get the "n" first words from a text, that to add a Read more ..
In this usage is needed to keep the punctuations, and also not break words.
Post Reply