How to make regex select strictly
'name'
: if searching for 'name',
'name_local'
: if searching for 'name_local',
but not to select both if searching for 'name'?
Tried '/('.$key.')(?!_)/'
, but it still selects both 'name'
and 'name_local'
if the $key
is name
.
You need word boundary anchor \b
:
'/(\b'.$key.'\b)/'
Word boundaries don't guarantee matching right piece of input string if for example the very next character isn't a word character e.g. name-local
. Use lookarounds:
(?<!\S)name(?!\S)
PHP:
$re = "/(?<!\S)$key(?!\S)/";