PHP How to extract part of given string?

vimaxvimaxyoo

New Member
I'm writing a search engine for my site and need to extract chunks of text with given keyword and few words around for the search result list.I ended with something like that:\[code\]/** * This function return part of the original text with * the searched term and few words around the searched term * @param string $text Original text * @param string $word Searched term * @param int $maxChunks Number of chunks returned * @param int $wordsAround Number of words before and after searched term */public static function searchTerm($text, $word=null, $maxChunks=3, $wordsAround=3) { $word = trim($word); if(empty($word)) { return NULL; } $words = explode(' ', $word); // extract single words from searched phrase $text = strip_tags($text); // clean up the text $whack = array(); // chunk buffer $cycle = 0; // successful matches counter foreach($words as $word) { $match = array(); // there are named parameters 'pre', 'term' and 'pos' if(preg_match("/(?P\w+){0,$wordsAround} (?P$word) (?P\w+){0,$wordsAround}/", $text, $match)) { $cycle++; $whack[] = $match['pre'] . ' ' . $word . ' ' . $match['pos']; if($cycle == $maxChunks) break; } } return implode(' | ', $whack); }\[/code\]This function does not work, but you can see the basic idea. Any suggestions how to improve the regular expression is welcome!
 
Back
Top