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 =>
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:
Implode the array into a string: $imploded=implode(" ", $myarray);.
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;
}
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
?>
I have same problem so try this...
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.
function check($string)
{
foreach($arr as $a) {
if(strpos($a,$string) !== false) {
return true;
}
}
return false;
}
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.
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": ""
}