0

I am creating a search for a keyword in a string of text. For example: Let's say I want to find the word 'Happy' and how many times it shows up in a book. Then I want to display 100 characters before and after the word, and do this for every word 'Happy' it finds.

I was able to find code to do it ONCE but how can I do this for all the occurrences of the keyword, in this case the word 'Happy'?

Here is the working code that finds one occurrence and displays characters before and after.

$text= $Content;
$find = 'Happy';
$result = strpos($text, $find);
echo substr($text,($result-100>0)?($result-100):0,100)." ".$find." "
.substr($text,$result+strlen($find),100); 

How I can do this in a loop and find all the occurrences of a keyword?

Papa De Beau
  • 3,744
  • 18
  • 79
  • 137

3 Answers3

1

According to this

this may help you finding second

$pos1 = strpos($haystack, $needle);
$pos2 = strpos($haystack, $needle, $pos1 + strlen($needle));

the third argument is the offset you search for the word. so default value is 0. and the +strlen($needle) adds the candidate word length to the last occurred position which is the starting point of $needle.

and then do this like recursively or sth

TheMMSH
  • 501
  • 6
  • 26
1

Following is case insensitive and works also with accented characters:

$out = [];
$find = 'Happy';
$charsBA = 100; // number of characters before / after
$offset = 0;
while(false !== ($pos = mb_stripos($text, $find, $offset, 'utf-8'))){
    $out[] = mb_substr($text, max(0, $pos-$charsBA), $charsBA*2+mb_strlen($find, 'utf-8'), 'utf-8');
    $offset = ++$pos;
}
print_r($out); // display found occurences
lubosdz
  • 4,210
  • 2
  • 29
  • 43
1

Maybe this is what you need?

$key="sed";
$string = "/([\s\S]{0,100})$key([\s\S]{0,100})/i";
$matches=null;
$paragraph = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?";

if (preg_match_all($string, $paragraph, $matches)) {
  echo count($matches[0]) . " matches found";
}else {
  echo "match NOT found";
}


var_dump($matches[0]);
koalaok
  • 5,075
  • 11
  • 47
  • 91