I am using PHP to find out whether a string, which starts with a special regular expression character, occurs as a word in a text string. This is the PHP code:
$subject = " hello [hello [helloagain ";
$pattern = preg_quote("[hello");
if (preg_match("/\b" . $pattern . "\b/", $subject, $dummy)) {
echo "match";
} else {
echo "no match";
}
The pattern starts with character [, hence, preg_quote() is used to escape it. There is an instance of [hello as a word in the subject so there should be one match, but the above preg_match() returns no match. I think the reason is that in the subject a special character is not recognized as the start or end of a word, but I can’t think of any way round this, any ideas? Thank you.
You are correct that a word boundary will not match between a space and a
[symbol.Instead of using a word boundary you can explicitly search for spaces (and other separators such as commas and periods if you wish) before and after the word: