Is there a simple way to check if a value is inside a string?
$string = ' 123,456,789,abc789,def'
if ($string has '789') {
// code
}
I only want an exact match (so only 789, not abc789)
The only way I can think of doing it at the moment is to explode the string using the comma to turn it into an array and then check each value for a match. Is there a better/more efficient way?
Using strpos won't work if for example you have ' 123,456,789,12789,abc,def'
, use preg_match instead :
$string = ' 123,456,789,abc789,def';
$what_to_find = '789';
if (preg_match('/\b' . $what_to_find . '\b/', $string)) {
// code
}
Demo
you could explode it and check if its in the array
function stringContains($string, $needle)
{
$arr = explode(',',$string);
if(in_array($needle,$arr))
return true;
return false;
}
aside from the stpos suggestions, this will not return true if you're looking for 12 in a string 123,456 where strpos will return a position
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With