note 110637 deleted from function.in-array by aharvey

From: Date: Mon, 19 Nov 2012 01:11:44 +0000
Subject: note 110637 deleted from function.in-array by aharvey
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192023@lists.php.net to get a copy of this message
Note Submitter: dieselpwr at yahoo dot com ---- This code to return true or false on SQL LIKE pattern (wildcard) search in array: //Example //Specify haystack $array = "House,Car,Boat,Horse,Pool Boy"; //Specify sql type like wildcard: %ou% $needle = '%zu%'; $array = explode(',', $array); $regex = like_to_regex($needle); $result = in_array_match($regex, $array); echo "haystack: "; print_r($array);echo "<br>"; echo "needle: ";print($needle)."<br>"; if($result == true){echo "result: true";}else{echo "result: false";}; //Example End function in_array_match($regex, $array) { if (!is_array($array)) trigger_error('Argument 2 must be array'); foreach ($array as $v) { $match = preg_match($regex, $v); if ($match === 1) { return true; }else{ return false; } } return false; } function like_to_regex($like, $casesensitive = FALSE, $escapechar = '\\') { $pattern = sprintf('~(?<!%1$s)(%1$s{2}|%%|_)~', preg_quote($escapechar)); $tokens = preg_split($pattern, $like, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); foreach($tokens as &$token) { switch($token) { case $escapechar.$escapechar: $token = preg_quote($escapechar); break; case '_': $token = '.'; break; case '%': $token = '.*'; break; default: $token = preg_quote($token); } } return sprintf('~^%s$~%s', implode('', $tokens), $casesensitive ? '':'i'); }

« previous php.notes (#192023) next »