views:

795

answers:

4

I have a body of text returned from a search query, lets call it $body. Now, what I want to do is for the script to find the first occurrence of the search query, $query. I know I can find this first occurrence this with strripos.

Once found, I want the script to return a couple of words before the first occurrence of the string as well as a few words after the end of the first occurrence.

Essentially I'm trying to do what Google does with it's search results.

Any ideas on where I should start? My issue is that I keep returning partial words.

+3  A: 

you could:

$words = explode(" ", $body);

creating an array of al the words in $body.

$index = array_search($query, $words);
$string = $words[$index - 1]." ".$words[$index]." ".$words[$index + 1];

But you would get into trouble if the query consist out of more than 1 word.

Bob Fanger
+1  A: 

I don't know PHP, but if you can use regular expressions you can use the following one:

string query = "search";
int numberOfWords = 2;
Regex(
       "([^ \t]+\s+){"
     + numberOfWords
     + "}\w*"
     + query
     + "\w*(\s+[^ \t]+){"
     + numberOfWords
     + "}"
);
Jader Dias
Tip: you should "escape" the query_string
Bob Fanger
A: 

how about a few words on either side:

<?php

$subject= "Four score and seven years ago, our forefathers brought forth upon this continent a new nation";
$pattern= "/(\w+\s){3}forth(\s\w+){3}/";

preg_match($pattern, $subject, $matches);

echo("... $matches[0] ...");

gives:

... our forefathers brought forth upon this continent ...
Scott Evernden
you should use preg_quote on the search word, as noted by NebyGemini in other comment.
OIS
A: 

Seems to me that you could use strpos to find the beginning of the search term and strlen to get its length, which would let you...

  • Create one array from the beginning of the text to the search term and then display the last word in that array and,
  • Create a second array from the words after strpos + strlen and display the first word in that array.

Or, if you've already got your hands on some number of characters before and after the search term, if you explode those into an array you can pull out one or two words.

Amanda