Skip to content
Advertisement

PHP Regex: Remove words not equal exactly 3 characters

An excellent “very close” answer at Remove words less than 3 chars with DEMO where Regex

b([a-z]{1,2})b

removes all words less than 3 chars.

But how to reset this demo vise versa ? to remove all words NOT EXACTLY EQUAL 3 chars ? We can catch word where exactly 3 chars by

b([a-z]{3})b

but how to tell regex – remove all other words what are NOT equal to 3 ?

So in regex demo ref above should leave only word ‘and’

Advertisement

Answer

Use alternatives to match either 1-2 or 4+ letters.

b(?:[a-z]{1,2}|[a-z]{4,})b
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement