note 24480 deleted from function.strpos by maxim

From: Date: Sat, 17 Aug 2002 22:46:27 +0000
Subject: note 24480 deleted from function.strpos by maxim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-35182@lists.php.net to get a copy of this message
function nthPos ($haystack, $needle, $n=1) { // finds the nth occurrence of any of $needle's characters in $haystack // returns -1 if not found; // $n negative => reverse search (starting from the end of $haystack) // e.g. $str = "c:\\winapps\\morph\\photos\\Party\\Phoebe.jpg"; // substr($str, nthPos($str, "/\\:", -2)) => \Party\Phoebe.jpg $pos = -1; $size = strlen($haystack); if ($reverse=($n<0)) { $n=-$n; $haystack = strrev($haystack); } while ($n--) { $bestNewPos = $size; for ($i=strlen($needle)-1;$i>=0;$i--) { $newPos = strpos($haystack, $needle[$i], $pos+1); if ($newPos===false) $needle = substr($needle,0,$i) . substr($needle,$i+1); else $bestNewPos = min($bestNewPos,$newPos); } if (($pos=$bestNewPos)==$size) return -1; } return $reverse ? $size-1-$pos : $pos; }

« previous php.notes (#35182) next »