Search code examples
phpregexpreg-matchtext-parsing

How to make preg_match to find whole word but not separate hyphen-words?


if (preg_match('#\b'.$rawword.'\b#i',$body)) {   

This code finds whole words, but if they are a hyphen word like "ABLE-BODIED" it will find ABLE and BODIED separately. How can modify the expression to accommodate for the dash?


Solution

  • You can use lookbehind and lookahead operators. This operators looks in behind and after but not match them.

    for example use \b(?<!-)xyz(?!-)\b for finding whole words of xyz that doesn't have - before or after.