PHP find a complex keyword (string) in a plain text
this might be a frequent question but my case is:
assuming my keyword is "black pepper" and my plain text is a recipe that contains the word "peppercorns"
i would like to be bale t开发者_StackOverflowo highlight the word peppercorns, not just pepper (eventhough this latter could be a good achievemet as well)
is it possible in php using preg_match? shoudl i split the keyword and craeate mutliple comparisons?
thanks
The question is slighly unclear. You want to highlight everything that is connected to black pepper? In the case of peppercorns that's easy because it's in one word together with pepper. But what if the text contains 'blackbirds', would you then highlight this word as well?
What you're trying to do needs intelligence or at least a complex lexical approach, you can't solve it with an algorithm.
If your keyword is only pepper, it becomes much easier, but only if pepper has only one meaning. In that case you could highlight everything that has pepper in it. But you would miss terms using more than one word. Here you would need a lexical approach again. If your engine knows that black pepper and white pepper are sub-patterns of pepper, then it works.
If you split the keywords and glue them together with carets you can use them as part of a simple regex:
$result = preg_replace("/(\w*(?:black|pepper)\w*)/i", "<b>$1</b>", $target_text);
EDIT: removed g from the regex flags, remembered it's functionality wrong
精彩评论