search a php array for partial string match

后端 未结 12 1437
南方客
南方客 2020-12-30 22:47

I have an array and I\'d like to search for the string \'green\'. So in this case it should return the $arr[2]

$arr = array(0 =>         


        
12条回答
  •  长发绾君心
    2020-12-30 23:38

    function findStr($arr, $str) 
    {  
        foreach ($arr as &$s) 
        {
           if(strpos($s, $str) !== false)
               return $s;
        }
    
        return "";
    }
    

    You can change the return value to the corresponding index number with a little modification if you want, but since you said "...return the $arr[2]" I wrote it to return the value instead.

提交回复
热议问题