regex - PHP How to extract part of given string? -


i'm writing search engine site , need extract chunks of text given keyword , few words around search result list. ended that:

 /**  * function return part of original text  * searched term , few words around 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 , 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 searched phrase         $text  = strip_tags($text);  // clean text         $whack = array(); // chunk buffer         $cycle = 0; // successful matches counter         foreach($words $word) {             $match = array();             // there named parameters 'pre', 'term' , '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);     } 
function not work, can see basic idea. suggestions how improve regular expression welcome!

never, never inject user content pattern of regex without using preg_quote sanitize input:

http://us3.php.net/manual/en/function.preg-quote.php


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -