Need assistance matching an exact string in PHP array

Go To


I have a text file that has item numbers in it (one per line). When an item is scanned by our barcode scanner it gets placed into this text file IF it exists in the order (which is stored in an array...item numbers only, nothing else).

What's happening is that if I have the two item numbers:

C0DB-9700-W C0DB-9700-WP

If I scan the item C0DB-9700-W first then I can scan the second item just fine, but if I scan C0DB-9700-WP first, it thinks that I've already scanned C0DB-9700-W because that item is a prefix to the item I've already scanned.

I know that strpos only checks for the first occurrence. I was using the following code:

if (strpos($file_array, $submitted ) !==FALSE) {

I switched to using:

if (preg_match('/'.$submitted.'/', $file_array)) {

I thought that by using preg_match I could overcome the problem, but apparently not. I just want PHP to check the EXACT string I give it against items in the array (which I'm getting from the file) to see if it has already been scanned or not. This isn't that hard in my mind but obviously I'm missing something here. How can I coax PHP into looking for the entire string and not giving up when it finds something that will be good enough (or at least what it thinks is good enough)?


2012-04-03 21:59
by Donavon Yelton
Have you try using pregmatchall - mamadrood 2012-04-03 22:02


There's nothing inexact about C0DB-9700-WP containing a match for C0DB-9700-W. What you're looking for is a regular expression that ensures the string you want is an entire word by itself:

if (preg_match('/\\b'.$submitted.'\\b/', $file_array)) {
2012-04-03 22:02
by mellamokb
This is exactly what I was looking for! Works like a charm! Thank you! - Donavon Yelton 2012-04-04 11:08


Just use in_array:

if (in_array($submitted, $file_array))

FYI, your regex was missing start/end anchors (and the second argument needs to be a string, not an array):

preg_match('/^'.$submitted.'$/', $subject)
2012-04-03 22:01
by webbiedave


For an array of items $file_array:

if (in_array($submitted, $file_array)) {
    // Do something...

Although in your examples, it looks like your $file_array is a string, so you'd want to do:

$file_array = explode("\n", $file_array);
2012-04-03 22:04
by Pete