-1

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.

Joey Martin
  • 369
  • 1
  • 3
  • 11
  • Who defines that these 2 words are together: `Heavy Rain` ?! Then when you have `Light Rain` it is different to: `Rain,Heavy` – Rizier123 Mar 12 '15 at 21:50
  • Why don't you store them in an array instead? – zerkms Mar 12 '15 at 21:51
  • So you only want it to return true when `$list="Rain"` and false for anything else? – Bankzilla Mar 12 '15 at 22:00
  • Thanks for the responses, except for the a$$ that voted it down. Seemed like a legitimate question to me. The LIST are possible weather conditions and the FIND is the current condition. If it doesn't match exactly then it's not a "severe". For example, it may currently be RAIN, but it's not Heavy Rain, so it shouldn't match. Will look at some of the code below. – Joey Martin Mar 12 '15 at 23:51

2 Answers2

2

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
castis
  • 8,154
  • 4
  • 41
  • 63
1

Try this:

$list="Light Rain,Heavy Rain";
$find="Light";
if(strpos($list,$find) !== false) 
{
    echo 'true';
}
else
{
    echo 'false';
}

Credits to: https://stackoverflow.com/a/4366748/4660348

Community
  • 1
  • 1
DarkZ3ro11
  • 128
  • 7