0

I have a PHP code to check a string inside collection of strings, my code something like this:

$string = '01122028K,02122028K,03122028M-1';
$search = '03122029M'
echo preg_match('/\b' . $search . '\b/', $string);

It returns TRUE...

How can I do with my regex to return it FALSE, I want it only return TRUE when the string in variable $search is actually match in variable $string, so $search = "03122029M" would return FALSE $search = "03122029M-1" would return TRUE

Thank you

Plipus Tel
  • 666
  • 3
  • 13
  • 23
  • look here http://stackoverflow.com/questions/5752829/regular-expression-for-exact-match-of-a-word – BenB Mar 13 '13 at 17:20

4 Answers4

1

Don't use a regular expression.

echo in_array($search, explode(',', $string));
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

The problem is with the boundary spearators you are using: \b includes the -.

You could separate on whitespaces and commans instead, using a character class. Also include the start of line, and of line in the test to catch cases at end of line:

preg_match('/(^|[\s,])' . $search . '([\s,]|$)/', $string);
Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
0

I don't think you really need a regular expression here. Moreover, you'd also be opening up yourself to an escaping nightmare.

If you add a comma to the start and end of $string, you can match the entire $search as a single entity by wrapping it in commas as well:

echo (strpos(',' . $string . ',', ',' . $search . ',') !== FALSE)
lc.
  • 113,939
  • 20
  • 158
  • 187
0

\b includes - in what you're matching. Match specifically off of commas instead - you can do this by just adding a comma to the start and end of the string.

$string = '01122028K,02122028K,03122028M-1';
$string = ','.$string.','
$search = '03122029M'
echo preg_match('/,' . $search . ',/', $string);
Wolfman Joe
  • 799
  • 1
  • 8
  • 23