37

我有一个数组,我想搜索字符串'green'。所以在这种情况下它应该返回$arr[2]

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

有没有像 in_array() 这样的预定义函数来完成这项工作,而不是遍历它并比较每个值?

4

11 回答 11

34

对于部分匹配,您可以迭代数组并使用类似strpos()的字符串搜索函数。

function array_search_partial($arr, $keyword) {
    foreach($arr as $index => $string) {
        if (strpos($string, $keyword) !== FALSE)
            return $index;
    }
}

对于完全匹配,使用in_array()

in_array('green', $arr)
于 2013-04-11T09:13:21.130 回答
29

您可以使用 php 的 preg_grep 函数。它在 PHP >= 4.0.5 中受支持。

$array = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
$m_array = preg_grep('/^green\s.*/', $array);

$m_array包含数组的匹配元素。

于 2013-04-11T09:15:07.080 回答
16

有几种方法...

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

使用循环搜索数组:

$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); }

使用 array_filter():

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

为了将闭包与其他参数一起使用,需要使用use-keyword。所以你可以抽象它并将它包装成一个函数:

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); }

这是一个工作示例:http ://codepad.viper-7.com/xZtnN7

于 2013-04-11T09:17:39.370 回答
5

PHP 5.3+

array_walk($arr, function($item, $key) {
    if(strpos($item, 'green') !== false) {
        echo 'Found in: ' . $item . ', with key: ' . $key;
    }
});
于 2013-04-11T09:19:51.040 回答
3

对于使用 '%needle%' 的类似 sql 进行搜索,您可以尝试使用

$input = preg_quote('gree', '~'); // don't forget to quote input string!
$data = array(
    1 => 'orange',
    2 => 'green string',
    3 => 'green', 
    4 => 'red', 
    5 => 'black'
    );
$result = preg_filter('~' . $input . '~', null, $data);

结果是

{
  "2": " string",
  "3": ""
}
于 2013-04-11T09:20:46.537 回答
0
function check($string) 
{
    foreach($arr as $a) {
        if(strpos($a,$string) !== false) {
            return true;
        } 
    }
    return false;
}
于 2013-04-11T09:14:45.900 回答
-1
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.

于 2013-04-11T09:15:30.213 回答
-1

在整个数组中快速搜索一个短语可能是这样的:

if (preg_match("/search/is", var_export($arr, true))) {
    // match
}
于 2017-05-12T21:38:42.233 回答
-1

为了找出数组中是否存在 UTF-8 不区分大小写的子字符串,我发现这种方法比使用 mb_strtolower 或 mb_convert_case 快得多:

  1. 将数组内爆成一个字符串:$imploded=implode(" ", $myarray); .

  2. 使用自定义函数将内爆字符串转换为小写: $lowercased_imploded = to_lower_case($imploded);

    函数 to_lower_case($str) {

$from_array=["A","B","C","D","E","F","G","H","I","J","K","L ","M","N","O","P","Q","R","S","T","U","V","W","X", "Y","Z","Ä","Ö","Ü","Õ","Ž","Š"];

$to_array=["a","b","c","d","e","f","g","h","i","j","k","l ","m","n","o","p","q","r","s","t","u","v","w","x", "y","z","ä","ö","ü","õ","ž","š"];

foreach($from_array as $key=>$val){$str=str_replace($val, $to_array[$key], $str);}

返回 $str;

}

  1. 使用普通 strpos 搜索匹配:if(strpos($lowercased_imploded, "substring_to_find")!==false){do something}
于 2017-05-26T09:13:45.053 回答
-1

这是一个用于普通或多维数组的函数。

  • 不区分大小写
  • 适用于普通数组和多维数组
  • 在发现全部或部分蜇伤时有效

这是代码(版本1)

function array_find($needle, array $haystack, $column = null) {

    if(is_array($haystack[0]) === true) { // check for multidimentional array

        foreach (array_column($haystack, $column) as $key => $value) {
            if (strpos(strtolower($value), strtolower($needle)) !== false) {
                return $key;
            }
        }

    } else {
        foreach ($haystack as $key => $value) { // for normal array
            if (strpos(strtolower($value), strtolower($needle)) !== false) {
                return $key;
            }
        }
    }
    return false;
} 

这是一个例子:

$multiArray = array(
     0 => array(
              'name' => 'kevin',
              'hobbies' => 'Football / Cricket'),
      1 => array(
              'name' => 'tom',
              'hobbies' => 'tennis'),
       2 => array(
              'name' => 'alex',
              'hobbies' => 'Golf, Softball')
);
$singleArray = array(
        0 => 'Tennis',
        1 => 'Cricket',
);

echo "key is - ". array_find('cricket', $singleArray); // returns - key is - 1
echo "key is - ". array_find('cricket', $multiArray, 'hobbies'); // returns - key is - 0 

仅适用于多维数组 - $column 与每个数组中的键名相关。如果 $needle 出现不止一次,我建议添加到此以将每个键添加到数组中。

如果您期望多个匹配项(版本 2) ,这是一个示例:

function array_find($needle, array $haystack, $column = null) {

    $keyArray = array();

    if(is_array($haystack[0]) === true) { // for multidimentional array

        foreach (array_column($haystack, $column) as $key => $value) {
            if (strpos(strtolower($value), strtolower($needle)) !== false) {
                $keyArray[] = $key;

            }
        }

    } else {
        foreach ($haystack as $key => $value) { // for normal array
            if (strpos(strtolower($value), strtolower($needle)) !== false) {
                $keyArray[] = $key;
            }
        }
    }

    if(empty($keyArray)) {
        return false;
    }
    if(count($keyArray) == 1) {
        return $keyArray[0];
    } else {
        return $keyArray;
    }

}

如果它只有一个匹配项,则返回键,但如果 $needle 在任何 $column 内有多个匹配项,则它将返回匹配键的数组。

希望这可以帮助 :)

于 2017-12-19T16:13:31.083 回答
-3
<?php
   $a=array("a"=>"red","b"=>"green","c"=>"blue");
   echo array_search("red",$a);
?>

我有同样的问题,所以试试这个......

于 2016-12-15T11:47:56.447 回答