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.
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.
$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
$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));
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.