Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value is inside string that has values separated by commas?

Tags:

php

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?

like image 350
user2413333 Avatar asked Dec 19 '22 23:12

user2413333


2 Answers

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

like image 153
OneOfOne Avatar answered Dec 22 '22 12:12

OneOfOne


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

like image 31
Bryan Avatar answered Dec 22 '22 12:12

Bryan