Word count search

Simple question here but I don’t know how to proceed.
I would like to get the number of searched words for all of the pages results.

Currently, I display all the results texts and I highlight all the words contained in these articles. So an article can contain several words that I am looking for.

My controller is classical

return function ($site) {

  $query   = get('q');
  $results = $site->search($query, 'title|text');

  return [
    'query'   => $query,
    'results' => $results,

and my highlighting function looks like

        $str = $result->text()->kt();
        $str = preg_replace("/\b([a-z]*${query}[a-z]*)\b/i","<mark>$1</mark>",$str);
        echo "$str";

I don’t understand what exactly you want to count. How often each word in the query string appears in the result set? So for example, if your result has three pages, and one of the search words appears 1 time in result one, 2 times in result 2, and 3 times in result 3, then the count would be 6?

Exactly ! :wink: I am looking for the number of iterations of the word in all the pages and not the number of pages containing at least this word

With substr_count() you can count the number of times a search term appears in a string.

So that means that for each result you would have to loop through the search field and add up your count…


Of course ! Thanks for your feddback.

$sum = 0;
foreach($results as $result)
     $sum+= substr_count(strtolower($result->text()), strtolower($query)); ; // case insensitive
echo $sum;