fpcjh
fpcjh

Reputation: 283

PHP regex to match whole words only, while not counting dashes as whole words

It's easy enough that /\b(test1|test2|test3)\b/i will match whole words, it's also matching them when part of a hyphenated word.

I'd like this to match:

foo test1 bar

But these not to:

foo-test1-bar
foo-test2 bar
foo test3-bar

Upvotes: 0

Views: 60

Answers (1)

anubhava
anubhava

Reputation: 784868

You can use lookarounds to prevent matching hyphenated words:

/(?<!-)\b(test1|test2|test3)\b(?!-)/i

RegEx Demo

Upvotes: 2

Related Questions