在 php 数组中搜索部分字符串匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15944824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:14:11  来源:igfitidea点击:

search a php array for partial string match

phparraysstringsearch

提问by Nivin

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

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

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

is there any predefined function like in_array() that does the job rather than looping through itand compare each values?

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

采纳答案by smitrp

You can use array_search function of php. It's supported in PHP >= 4.0.5.

您可以使用 php 的 array_search 函数。PHP >= 4.0.5 支持它。

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

$m_arraycontains matched elements of array.

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

回答by n a

For a partial matchyou can iterate the array and use a string search function like strpos().

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

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

For an exact match, use in_array()

对于精确匹配,使用in_array()

in_array('green', $arr)

回答by Quasdunk

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():

使用 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:

为了将闭包与其他参数一起使用,需要使用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); }

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

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

回答by Kotzilla

for search with like as sql with '%needle%' you can try with

对于像 sql with '%needle%' 的搜索,您可以尝试使用

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

and result is

结果是

{
  "2": " string",
  "3": ""
}

回答by dev_dodiya

<?php
   $a=array("a"=>"red","b"=>"green","c"=>"blue");
   echo array_search("red",$a);
?>

I have same problem so try this...

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

回答by MrCode

PHP 5.3+

PHP 5.3+

array_walk($arr, function($item, $key) {
    if(strpos($item, 'green') !== false) {
        echo 'Found in: ' . $item . ', with key: ' . $key;
    }
});

回答by Louis.CLast

function check($string) 
{
    foreach($arr as $a) {
        if(strpos($a,$string) !== false) {
            return true;
        } 
    }
    return false;
}

回答by hirre

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.

如果需要,您可以通过稍加修改将返回值更改为相应的索引号,但是由于您说“...返回 $arr[2]”,我将它写为返回值。

回答by phoenix

A quick search for a phrase in the entire array might be something like this:

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

if (preg_match("/search/is", var_export($arr, true))) {
    // match
}

回答by Andrei Kravtsov

In order to find out if UTF-8 case-insensitive substring is present in array, I found that this method would be much faster than using mb_strtolower or mb_convert_case:

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

  1. Implode the array into a string: $imploded=implode(" ", $myarray);.

  2. Convert imploded string to lowercase using custom function: $lowercased_imploded = to_lower_case($imploded);

    function to_lower_case($str) {

  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","?","?","ü","?","?","?"];

$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","?","?","ü","?","?","?"];

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

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

return $str;

返回 $str;

}

}

  1. Search for match using ordinary strpos: if(strpos($lowercased_imploded, "substring_to_find")!==false){do something}
  1. 使用普通的 strpos 搜索匹配项:if(strpos($lowercased_imploded, "substring_to_find")!==false){do something}