Search code examples
phppreg-matchstrpos

Check to see if EXACT value is in a string - PHP


I have read numerous posts about how to see if a value is in a string. Apparently my request is different since the multiple bits of code haven't worked 100%.

I am searching a string and need to make sure the EXACT value is in there - with a perfect match.

$list="Light Rain,Heavy Rain";
$find="Rain";

That should NOT match for what I need to do. I need it to match exactly. All the code I have tested says it IS a match - and I understand why. But, what can I do to make it not match since Rain is different than Light Rain or Heavy Rain? I hope I am making sense.

I have already tried strpos and preg_match, but again, those equal a match - but for my purposes, not an equal match.

Thanks for something that probably will end up being a DUH moment.


Solution

  • If you need exact matches and the $list is always comma delimited. Why not check for them this way?

    $list = explode(',', "Light Rain,Heavy Rain");
    
    var_dump(in_array('Rain', $list)); // false
    var_dump(in_array('Heavy Rain', $list)); // true
    

    and if you must have a regular expression.

    in your regex, make sure you're checking for the start of the string or a comma (^|,) at the start, and then your string, then another comma or the end of the string (,|$). The ?: makes them non-capturing groups so they dont show up in $matches.

    $list = "Light Rain,Heavy Rain";
    
    $test = 'Rain';
    preg_match("/(?:^|,)($test)(?:,|$)/", $list, $matches);
    var_dump(!empty($matches)); // false
    
    $test = 'Heavy Rain';
    preg_match("/(?:^|,)($test)(?:,|$)/", $list, $matches);
    var_dump(!empty($matches)); // true