search a php array for partial string match

后端 未结 12 1527
南方客
南方客 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}

提交回复
热议问题