Question

What i'm trying to do is search for a word (or couple of words) and then return a string of 5 words before, and 5 words after the keyword.

My PHP code is like this:

function getPreview($keyWord, $searchArea) {
    preg_match("/(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?$keyWord ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)?/i", $searchArea, $result);
    foreach ($result as $res) {
        return preg_replace("/$keyWord/", "<B>$keyWord</B>", $res);
        break;
    }
}

The only problem is, when there aren't 5 words before, or after, PHP doesn't return this.

Does anyone know how I can make this more dynamicly? So PHP knows how many words there are..?

Thx!

Was it helpful?

Solution

This is what you want i guess:

$re = '/((\w* ){0,5})(keyWord)(( \w*){0,5})/i'; 
$str = 'klaus steven keyword peter holger und so weiter und so fort'; 

preg_match_all($re, $str, $matches);

It has "word followed by space" for 0 to 5 times, then your keyword and then another "space followed by word" for 0 to 5 times.

See it working with more information here

OTHER TIPS

If you want to stick with regular expressions, this one can work with less words. Also, you'd want to escape the keywords in case it contains a question mark or any other regex char.

$escapedKeyword = preg_quote($keyWord,'/');
preg_match("/(\w+ ){0,5}?$escapedKeyword( \w+){0,5}/", $searchArea, $result);

The ? marker after the {0,5} quantifier, makes it ungreedy. Meaning it will try to take as few words as possible before the match, enabling it to work when there are less than 5 words preceding the keyword.

Also you might want to look into preg_match_all and work on the replacement code.

I think a better solution is using an explode, then make an array_search in the resulted array. This array is numerically indexed so you can simply know how many words are before and after your answer. Something like this could work (not tested) :

<?php
function getPreview($keyWord, $searchArea) {
    $results = explode(' ', $str);
    $indexOfMyKeyword = array_search($keyword, $results);
    $before = array_slice($results, $indexOfMyKeyword, -5);
    $after = array_slice($results, $indexOfMyKeyword, 5);
    return implode(' ', $before).' '.$keyword.' '.implode(' ', $after);
}

You can optionnaly check if your keyword is present using in_array before trying to extract his position with array_search.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top