Hi guys could you please help me to resolve this riddle?
I have an array of keywords pretty big one that I use to match those keywords in content.
Example: $array('game','gamers','gaming'); etc...
I am using this foreach method to loop though each keyword and match it against content but in some cases content can be really big and more than 50 keywords and more than 20 posts per page slows the site down dramatically.
foreach($array as $key => $vall)
{
$pattern = '/\b'.$vall.'\b/';
$data['content'] = preg_replace($pattern, " <a style=\"font-weight: bold;color:rgb(20, 23, 26);\" href=\"".$url."\">".$vall."</a>", $data['content'],1);
}
The good thing about is that I can specify replace limit to one means that it will not replace all instances of that keyword.
The method above is not performance effective.
My other approach is this but there is an issue. I can't specify limit.
$pattern = '/\bgamers|gaming|gamer\b/';
$data['content'] = preg_replace($pattern, " <a style=\"font-weight: bold;color:rgb(20, 23, 26);\" href=\"".$url."\">$0</a>", $data['content']);
The method above works great but it replaces all instances of matched keywords.
Question. How can I add to pattern keywords separated by or expression and then replace only first match of each keyword.
Update.
$string = 'I am a gamer and I love playing video games. Video games are awesome. I have being a gamer for a long time. I love to hang-out with other gamer buddies of mine.';
$keyWordsToMatch = 'gamer,games';
For the output it needs to replace only forst instance of $keyWordsToMatch.
Like this:
$string = 'I am a (gamer)_replace and I love playing video (games)_replace. Video games are awesome. I have being a gamer for a long time. I love to hang-out with other gamer buddies of mine.';
$pattern = '/\bgamers|gaming|gamer\b/';is a typo. You need$pattern = '/\b(?:gamers|gaming|gamer)\b/';$data['content'] = preg_replace($pattern, " <a style=\"font-weight: bold;color:rgb(20, 23, 26);\" href=\"".$url."\">$0</a>", $data['content']);. But I guess the problem is with the number of words, the pattern gets too long for PCRE.