search a php array for partial string match

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

    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:

    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) {

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

    return $str;

    }

    1. Search for match using ordinary strpos: if(strpos($lowercased_imploded, "substring_to_find")!==false){do something}
    0 讨论(0)
  • 2020-12-30 23:31
    <?php
       $a=array("a"=>"red","b"=>"green","c"=>"blue");
       echo array_search("red",$a);
    ?>
    

    I have same problem so try this...

    0 讨论(0)
  • 2020-12-30 23:36

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

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

    $m_array contains matched elements of array.

    0 讨论(0)
  • 2020-12-30 23:37
    function check($string) 
    {
        foreach($arr as $a) {
            if(strpos($a,$string) !== false) {
                return true;
            } 
        }
        return false;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-30 23:39

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

    $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": ""
    }
    
    0 讨论(0)
提交回复
热议问题