0

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.

macropod
  • 12,757
  • 2
  • 9
  • 21
Yogita
  • 170
  • 9
  • Try quoting the string first: `'/\b'.preg_quote($model).'\b/';` - That escapes any characters that has special meaning in regex. However, if you just want to check if a string occurs in another string, you don't need regex. In PHP 8, you can use [str_contains()](https://www.php.net/manual/en/function.str-contains.php) and pre PHP 8, you can use [strstr()](https://www.php.net/manual/en/function.strstr.php) – M. Eriksson Feb 09 '22 at 18:44
  • Did you give up? – AbraCadaver Mar 15 '22 at 20:23

2 Answers2

0

Two issues:

  1. Believe it or not . is not a word boundary \b
  2. 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, '/').'/';
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563