Suppose I have a string like:
$str ="Model number is FM223-56/89.";
And I want match the model number only in this string via preg_match.
I am doing it like:
$model ="FM223-56/89.";
$pattern = '/\b'.$model.'\b/';
echo preg_match($pattern, $str);
But no luck, I want to search word that can have .-,'/" in it, Is it possible to search via preg_match?
There is no fixed pattern.
CodePudding user response:
Two issues:
- Believe it or not
.is not a word boundary\b - You are using
/as a delimiter but there is a/in your pattern
So either use a different delimiter:
$pattern = "~\b".$model."~";
Or better, escape the variable and specify your delimiter:
$pattern = '/'.preg_quote($model, '/').'/';
CodePudding user response:
You need adaptive dynamic word boundaries, i.e. only apply word boundaries if the neighboring chars are word chars:
$str ="Model number is FM223-56/89.";
$model ="FM223-56/89.";
$pattern = '/(?!\B\w)' . preg_quote($model, '/') . '(?<!\w\B)/';
echo preg_match($pattern, $str); // => 1
See the PHP demo.
(?!\B\w)- checks if the next char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required(?<!\w\B)- checks if the previous char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required.
Note the preg_quote($model, '/') part: it escapes all special chars in the $model string and also the / char that is used as a regex delimiter char.
