0

I'm trying to find if a substring exists inside of a larger string. The match has to be exact. Most of the time it works be in the scenario below it says its an exact match even though it is not.

$partnumber = "4.7585";
$productname = "Eibach 4.7585.880 Sport Plus Kit"

if(preg_match('/^.*(\b'.$partnumber.'\b).*$/i', $productname)){
      echo "****************Exact Match****************";
}

It should only match if the $partnumber = '4.7585.880';

As a note, the partnumber could change, it could contain numbers, letters, decimals or dashes.

Jason Small
  • 1,064
  • 1
  • 13
  • 29

2 Answers2

2

you need to escape $partnumber using preg_quote():

$partnumber = "4.7585";
$productname = "Eibach 4.7585.880 Sport Plus Kit"

if(preg_match('/[^\B\.]'.preg_quote($partnumber).'[^\B\.]/i', $productname)){
    echo "****************Exact Match****************";
}

I've also simplified your regular expression by just searching for the partnumber instead of the start and end of the line and everything that might be surrounding it.

DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70
1

The \b regex identifier matches word boundaries. A word character is defined as [a-zA-Z0-9_], and so the \b will match the boundary between any word character and any non-word character. It will also match the start (or end) of the string if the first (or last) character is a word character. (See here for more.)

In your example, the second '.' is a non-word character, so it matches your regex. If the part number will always be in the middle of a sentence, you could use \s to match whitespace around it. If it could possibly be at the end of the sentence (ie, followed by a '.') then I think you will need a more complicated regex which can look at the characters following the match to check if the match is complete or not.

Also, as Omar Jackman said, you do need to escape the part number. In your example provided, the product name 'Eibach 4X7585 Sport Plus Kit' would also match, since the '.' in the part number would be interpreted as part of the regex. As per this question, preg_quote is the php function you're looking for to do that.

Community
  • 1
  • 1
Dallin
  • 600
  • 3
  • 11