0

After reading here and after trying preg_quote, I understand the error and I understand that I must use delimiters.

The problem is one of the delimiter is a forward slash which is also part of the string that I'm trying to compare. I do not understand how to fix my problem. Where do I put the delimiters in my code?

I'm using preg_match to identify a given product with the product name as follow :

if (preg_match("/\b$productcolor\b/i", "$searchProductName")) { 

//do something
}

This works well if the product name looks like this :

$searchProductName = Yupoong 6606 Retro Trucker Cap (Red);//$_POST
$productcolor = 'Red';//$_POST

Preg_match returns unknown modifier if there is a forward slash in the name like this :

$searchProductName = Yupoong 6606 Retro Trucker Cap (Rust Orange/ Khaki);//$_POST
$productcolor = 'Rust Orange/ Khaki';//$_POST

I'm trying to get over that problem by eliminating the forward slash like this :

$productColor = str_replace('/', ' ', $productcolor);

This will return a string like this Rust Orange Khaki. But removing the forward slash makes preg_match not matching the color in the name.

How can I solve this problem? Mind you, NOT all products have a forward slash in their name. Some have single colors.

  • 1
    https://www.php.net/manual/en/regexp.reference.delimiters.php Use a different delimeter. – Tim Morton Jul 05 '19 at 03:47
  • Either as already mentioned change the delimiter or escape the regex (passing in the delimiter your using - https://stackoverflow.com/questions/1531456/is-there-a-php-function-that-can-escape-regex-patterns-before-they-are-applied) – Nigel Ren Jul 05 '19 at 05:30
  • Please take a look at Toto answer (that perfectly answers your question) and accept it. – Casimir et Hippolyte Jul 07 '19 at 21:58

1 Answers1

1

preg_quote is your friend. It escapes special characters.

if (preg_match("/\b" . preg_quote($productcolor, "/") . "\b/i", $searchProductName)) { 
    //do something
}
Toto
  • 89,455
  • 62
  • 89
  • 125