title: Keyword matching optimization
body: <p>In my website there is an option to search for archived articles. It works fine, but what I want to do now is to highlight the matching words in the results previews' snippets (like <a href="http://www.google.com" rel="nofollow">Google</a> does).</p>
  
  <pre><code>$keywords = explode( $query );
  </code></pre>
  
  <p>In <code>$keywords</code> I store the keywords of the search query. And then, when preparing each result to be shown, I do the following:</p>
  
  <pre><code>$exploded  = explode( ' ', $text );
  $count     = count( $exploded );
  $text      = ''; // clears the text
  
  for ( $i = 0; $i &lt; $count; $i++ ) {
      if ( preg_grep( "/{$exploded[$i]}/i", $keywords ) ) {
          $exploded[$i] = '&lt;strong&gt;' . $exploded[$i] . '&lt;/strong&gt;';
      }
  
      $text .= $exploded[$i] . ' ';
  }
  </code></pre>
  
  <p>Where <code>$text</code> is the text for the current result's preview snippet. So basically, if a word matches (case insensitive-ly) it becomes surrounded by a <a href="http://www.w3.org/wiki/HTML/Elements/strong" rel="nofollow">strong element</a>.</p>
  
  <p>My question is: is there a way to optimize this further? Because this script, which is <code>O(n^2)</code> (because of the <a href="http://php.net/manual/en/function.preg-grep.php" rel="nofollow">preg_grep</a> calls inside the for loop) is executed for each of the results, that would make the whole script <code>O(n^3)</code>. And <code>O(n^3)</code> is <em>a lot</em> in a practical situation.</p>