Bhavesh Tilvani
Bhavesh Tilvani

Reputation: 193

Regex to match words starting with hyphen

I have a regex which does all matches except one match.The PHP Code for the word match is:

$string = preg_replace("/\b".$wordToMatch."\b/","<span class='sp_err' style='background-color:yellow;'>".$wordToMatch."</span>",$string); 

Here in the above regex when the $wordToMatch variable value becomes "-abc" and the $string value is "The word -abc should match and abc-abc should not match".With above regex it fails to catch "-abc".

Upvotes: 2

Views: 1308

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627449

In case your keywords can have non-word characters on both ends you can rely on lookarounds for a whole word match:

"/(?<!\\w)".$wordToMatch."(?!\\w)/"

Here, (?<!\w) will make sure there is no word character before the word to match, and (?!\w) negative lookahead will make sure there is no word character after the word to match. These are unambiguous subpatterns, while \b meaning depends on the context.

See regex demo showing that -abc is not matched in abc-abc and matches if it is not enclosed with word characters.

PHP demo:

$wordToMatch = "-abc";
$re = "/(?<!\\w)" . $wordToMatch . "(?!\\w)/"; 
$str = "abc-abc -abc"; 
$subst = "!$0!"; 
$result = preg_replace($re, $subst, $str);
echo $result; // => abc-abc !-abc!

Upvotes: 1

Related Questions