note 24480 added to function.strpos

From: Date: Sat, 17 Aug 2002 20:22:50 +0000
Subject: note 24480 added to function.strpos
Groups: php.notes 
Request: Send a blank email to php-notes+get-35174@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; } -- http://www.php.net/manual/en/function.strpos.php http://master.php.net/manage/user-notes.php?action=edit+24480 http://master.php.net/manage/user-notes.php?action=delete+24480 http://master.php.net/manage/user-notes.php?action=reject+24480

« previous php.notes (#35174) next »