Search code examples
phpregexpreg-match

Faster alternative to preg_match while maintaining search logic


I'm having a few problems with the speed of a search function I have created.

My search uses preg_match to separate keywords from a text. It can search for "Intern" but not "Internet" or "International".

But it runs really slow, is there anyway you can speed kind of function up?

 foreach ($keywords as $Word)
 {
   if (preg_match("/\S*\b($Word)[s]?\b\S*/i", $Text))
   {
     return $Word;
   }
 }

Thanks :)


Solution

  • By removing the first \S* the expression will be fast enough already. The second one is also redundant in your preg_match.

    You also need to double-escape special regex metacharacters inside a double-quoted PHP regex.

    Use

    foreach ($keywords as $Word)
     {
       if (preg_match("/\\b(" . preg_quote($Word) . ")s?\\b/i", $Text))
       {
         return $Word;
       }
     }
    

    See this IDEONE demo

    Note that if you have special characters (like [ or () inside the $keywords array, you need to use "/(?<!\\w)(" . preg_quote($Word) . ")s?(?!\\w)/i" regex.