Michael
Michael

Reputation:

Return words before and after the first occurrence of a string

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.

Upvotes: 2

Views: 3982

Answers (4)

Bob Fanger
Bob Fanger

Reputation: 29897

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.

explode - array_search

Upvotes: 3

Amanda
Amanda

Reputation: 12737

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.

Upvotes: 2

Scott Evernden
Scott Evernden

Reputation: 39950

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 ...

Upvotes: 0

Jader Dias
Jader Dias

Reputation: 90465

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
     + "}"
);

Upvotes: 2

Related Questions