sir.otasek
sir.otasek

Reputation: 41

PHP How to extract part of given string?

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:


/**
 * 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);
    }
This function does not work, but you can see the basic idea. Any suggestions how to improve the regular expression is welcome!

Upvotes: 0

Views: 795

Answers (2)

mcgrailm
mcgrailm

Reputation: 17640

why re-invent the wheel here doesn't google have the best search engine I would look at their appliance

Upvotes: 1

Oxyrubber
Oxyrubber

Reputation: 171

Never, never inject user content into the pattern of a RegEx without using preg_quote to sanitize the input:

https://www.php.net/manual/en/function.preg-quote.php

Upvotes: 1

Related Questions