search a php array for partial string match

后端 未结 12 1276
南方客
南方客 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:46

    There are several ways...

    $arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
    

    Search the array with a loop:

    $results = array();
    
    foreach ($arr as $value) {
    
      if (strpos($value, 'green') !== false) { $results[] = $value; }
    
    }
    
    if( empty($results) ) { echo 'No matches found.'; }
    else { echo "'green' was found in: " . implode('; ', $results); }
    

    Use array_filter():

    $results = array_filter($arr, function($value) {
        return strpos($value, 'green') !== false;
    });
    

    In order to use Closures with other arguments there is the use-keyword. So you can abstract it and wrap it into a function:

    function find_string_in_array ($arr, $string) {
    
        return array_filter($arr, function($value) use ($string) {
            return strpos($value, $string) !== false;
        });
    
    }
    
    $results = find_string_in_array ($arr, 'green');
    
    if( empty($results) ) { echo 'No matches found.'; }
    else { echo "'green' was found in: " . implode('; ', $results); }
    

    Here's a working example: http://codepad.viper-7.com/xZtnN7

提交回复
热议问题