note 42627 added to function.in-array

From: Date: Mon, 24 May 2004 14:51:18 +0000
Subject: note 42627 added to function.in-array
Groups: php.notes 
Request: Send a blank email to php-notes+get-70023@lists.php.net to get a copy of this message
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 *****/ ---- Manual Page -- http://www.php.net/manual/en/function.in-array.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+42627 Delete -- http://master.php.net/manage/user-notes.php?action=delete+42627&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+42627&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#70023) next »