Ricky Barnett
Ricky Barnett

Reputation: 1170

php - regex exact matches

I have the following strings:

Falchion-Case
P90-ASH-WOOD-WELL-WORN

I also have the following URLS which are inside a text file:

http://csgo.steamanalyst.com/id/115714004/FALCHION-CASE-KEY-
http://csgo.steamanalyst.com/id/115716486/FALCHION-CASE-
http://csgo.steamanalyst.com/id/2018/P90-ASH-WOOD-WELL-WORN

I'm looping through each line in the text file and checking if the string is found inside the URL:

// Read from file
if (stristr($item, "stattrak") === FALSE) {
    $lines = file(public_path().'/csgoanalyst.txt');
    foreach ($lines as $line) {
    // Check if the line contains the string we're looking for, and print if it does
        if(preg_match('/(?<!\-)('.$item.')\b/',$line) != false) {  // case insensitive
            echo $line;
            break;
        }
    }
}

This works perfectly when $item = P90-ASH-WOOD-WELL-WORN however when $item = Falchion-Case It matches on both URL's when only the second: http://csgo.steamanalyst.com/id/115716486/FALCHION-CASE- is valid

Upvotes: 1

Views: 272

Answers (2)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

Try modifying your regx to match the end of the line, assuming the line ends

 '/('.$item.')$/'

This would match

  http://csgo.steamanalyst.com/id/115714004/FALCHION-CASE-KEY- <<end of line

Basically do an ends with type match, you can do this too

   '/('.$item.')\-?$/'

to optionally match an ending hyphen

Upvotes: 1

anubhava
anubhava

Reputation: 784998

You can also use a negative lookahead to negate that unwanted case:

preg_match('/(?<!-)'. preg_quote($item) .'(?!-\w)/i', $line);

Upvotes: 0

Related Questions