You almost got it 🙂
roice;10941169 wrote:
preg_match_all('/$keyword[a-z]{15}/', $content, $matches, PREG_SET_ORDER))
Looking at the pattern, the first thing you have to learn is the difference beteween using " and ' as string delimiters. No parsing of the string is done when using sinlge quote, which means that the part actually tries to match $keyword, not the value of the $keyword variable.
The character class [a-z] only matches lower case letters (unless you use the pattern modifier i). To match both lc and uc chars, use [a-zA-Z]
Repetition like {15} matches exactly the speicfied number. So if dog appeared towards the end of the string, with less than 15 remaining lc letters, the pattern would not match. Using {0, 15} means anywhere from 0 to 15 characters will be matched. But, since punctuations and digits might appear, I'd rather just match anything, and to include newlines in "anything", we'll add the dot_all modifier s.
And by the same reasoning as above, let's add this before the actual keyword as well.
Which gives
$content = "all the pets like food but dogs especially like to eat meat and more. In addition it important to know that dogs don't realy like to take a shower";
$keyword = 'dog';
if (preg_match_all('/.{0,15}'.$keyword.'.{0,15}/', $content, $matches))
{
foreach($matches[0] as $match)
{
$match = htmlspecialchars($match);
echo "<br />";
echo "match:"; echo str_replace($keyword, '<b>'.$keyword.'</b>',$match);
}
}
Ah, I also dropped the PREG_SET_ORDER, but that's a matter of personal preference. The ordinary order makes more sense to me.
Regexps aside, this can also be done with strpos