note 42627 deleted from function.in-array by aidan
| From: | aidan@php.net | Date: | Wed, 18 Aug 2004 06:22:42 +0000 |
| Subject: | note 42627 deleted from function.in-array by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-74850@lists.php.net to get a copy of this message | ||
Note Submitter: sam d o t fullman (AT) verizon do t net
----
function in_array_enhanced($needle, $hay, $insensitive=true, $regex=0){
/**
This function could be developed further and enhances in_array()
regex=0 -- don't use regex to evaluate
regex=1 -- evaluate the needle as a regex against each element of the array
regex=2 -- treat each element of the ARRAY as a regex, and evaluate needle against them
**/
//I always globalize a variable by my function name for flags
global $in_array_enhanced;
$insensitive?$needle=strtolower($needle):'';
if(@!is_array($hay)){
$in_array_enhanced[err]='No array present, or no elements in array';
return false;
}
foreach($hay as $v){
$insensitive?$v=strtolower($v):'';
//note the ^ and $ to ensure we don't have a partial match but the whole string, this could
be modified by a switch
$fullString=true;
if($fullString){
$s='^';$f='$';
}
if($regex==1){
if(preg_match('/'.$s.$needle.$f.'/',$v)){
return true;
}
}else if($regex==2){
if(preg_match('/'.$s.$v.$f.'/',$needle)){
return true;
}
}else{
if($v==$needle){
return true;
}
}
}
//if not successful
return false;
}
/****
Examples of enhanced use:
$array=Array('.*apple.*','red','blue');
$str='candy apple red';
echo in_array_enhanced($str,$array,1,2);
#(returns true because of the first value of the array, note 'candy apple red' is checked
against .*apple.*, not vice versa)
$array=Array('candy apple red','soda pop','whatever you want');
$str='.*apple*.';
echo in_array_enhanced($str,$array,1,1);
#(in this case, the haystack values are checked against the needles
*****/