domnissient
domnissient

Reputation: 110

PHP Regex matching words and keyphrases

Ok I need a one line php-ready regex that encompasses a number of keywords, and keyterms and will match at least one of them. For example:

Keyterms:
* "apple"
* "banana"
* "strawberry"
* "pear cake"

Now if any of these key terms are found then it returns true. However, to add a little more difficulty here, the "pear cake" term should be split as two keywords which must both be in the string, but need not be together.

Example strings which should return true:
* A great cake is made from pear
* i like apples
* i like apples and bananas * i like cakes made from pear and apples
* I like cakes made from pears

Note. that i do not require the end word boundary to allow for plurals etc...

Thanks for your help, just cannot get my head around regex...

Upvotes: 0

Views: 377

Answers (2)

Pravin
Pravin

Reputation: 1059

How about:

/apple|banana|strawberry|pear.*?cake|cake.*?pear/

If you want to match apples or apple, cakes or cake. Then add \b to every word and add s?\b at the end.

Upvotes: 0

Daren Schwenke
Daren Schwenke

Reputation: 5478

/\bapple|\bbanana|\bstrawberry|\bpear.*?\bcake|\bcake.*?\bpear/

if you don't require beginning word boundaries either remove the \b's, but then cranapple would match as well.

Upvotes: 1

Related Questions