user198989
user198989

Reputation: 4665

Get sentence(s) which include(s) searched word(s)?

I want to get sentence(s) which include(s) searched word(s). I have tried this but can't make it work properly.

$string = "I think instead of trying to find sentences, I'd think about the amount of 
context around the search term I would need in words. Then go backwards some fraction of this number of words (or to the beginning) and forward the remaining number 
of words to select the rest of the context.";

$searchlocation = "fraction";

$offset = stripos( strrev(substr($string, $searchlocation)), '. ');
$startloc = $searchlocation - $offset;
echo $startloc;

Upvotes: 1

Views: 1031

Answers (3)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57660

using array_filter function

$sentences = explode('.', $string);
$result = array_filter(
    $sentences, 
    create_function('$x', "return strpos(\$x, '$searchlocation');"));

Note: the double quote in the second parameter of create_function is necessary.

If you have anonymous function support, you can use this,

$result = array_filter($sentences, function($x) use($searchlocation){
        return strpos($x, $searchlocation)!==false;
});

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Since you reverse the string with strrev(), you will find [space]. instead of .[space].

Upvotes: 1

Mihai Iorga
Mihai Iorga

Reputation: 39704

You can get all sentences.

try this:

$string = "I think instead of trying to find sentences, I'd think about the amount of 
context around the search term I would need in words. Then go backwards some fraction of this number of words (or to the beginning) and forward the remaining number 
of words to select the rest of the context.";

$searchlocation = "fraction";

$sentences = explode('.', $string);
$matched = array();
foreach($sentences as $sentence){
    $offset = stripos($sentence, $searchlocation);
    if($offset){ $matched[] = $sentence; }
}
var_export($matched);

Upvotes: 3

Related Questions