codealfa
codealfa

Reputation: 91

PHP Regex to match word in a sentence with optionally only other certain words

I'm looking for a PHP regex to match a word in a sentence that will also optionally permit some other words in the sentence but the match should fail if there are any other words in the sentence that are not in the allowed list. For eg:

The quick fox

Here I'm looking for fox. 'The' and 'quick' are ok too if they appear. Since those words are optional then just

fox 

would be ok too. However,

The quick brown fox

is not ok. I don't want a brown fox.

Feel free to suggest another way of doing this too but it needs to be blazing fast.

EDIT: The words will come before fox but they can appear in any order so

 quick The fox

should match too.

Upvotes: 0

Views: 109

Answers (2)

codealfa
codealfa

Reputation: 91

Ok I think I found a solution that's not too complicated and so far as I've tested, it seems to work with the results I want

 ^(?(?=\b)(?:The|quick|\W)|.)+?fox

I'm checking here at each character to see if it's a word boundary. If it is then you must match 'the' or 'quick' or a non-word character at that point (indicating you're at the end of the word). This will go on until I match 'fox'. If I match any other words than the ones allowed the match fails.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Just make the first two words as optional.

^(?:(?:The )?(?:quick )?fox|(?:quick )(?:The )?fox|(?:fox )?(The )?quick|(?:The )?(?:fox )?quick)$

Upvotes: 1

Related Questions