note 58934 modified in function.strpos by danbrown

From: Date: Sun, 17 May 2009 16:38:04 +0000
Subject: note 58934 modified in function.strpos by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154868@lists.php.net to get a copy of this message
<?php function nthPos ($str, $needles, $n=1) { // finds the nth occurrence of any of $needles' characters in $str // returns -1 if not found; $n<0 => count backwards from end // e.g. $str = "c:\\winapps\\morph\\photos\\Party\\Phoebe.jpg"; // substr($str, nthPos($str, "/\\:", -2)) => \Party\Phoebe.jpg // substr($str, nthPos($str, "/\\:", 4)) => \photos\Party\Phoebe.jpg $pos = -1; $size = strlen($str); if ($reverse=($n<0)) { $n=-$n; $str = strrev($str); } while ($n--) { $bestNewPos = $size; for ($i=strlen($needles)-1;$i>=0;$i--) { $newPos = strpos($str, $needles[$i], $pos+1); if ($newPos===false) $needles = substr($needles,0,$i) . substr($needles,$i+1); else $bestNewPos = min($bestNewPos,$newPos); } if (($pos=$bestNewPos)==$size) return -1; } return $reverse ? $size-1-$pos : $pos; } ?> Csaba Gabor from Vienna --was-- function nthPos ($str, $needles, $n=1) { // finds the nth occurrence of any of $needles' characters in $str // returns -1 if not found; $n<0 => count backwards from end // e.g. $str = "c:\\winapps\\morph\\photos\\Party\\Phoebe.jpg"; // substr($str, nthPos($str, "/\\:", -2)) => \Party\Phoebe.jpg // substr($str, nthPos($str, "/\\:", 4)) => \photos\Party\Phoebe.jpg $pos = -1; $size = strlen($str); if ($reverse=($n<0)) { $n=-$n; $str = strrev($str); } while ($n--) { $bestNewPos = $size; for ($i=strlen($needles)-1;$i>=0;$i--) { $newPos = strpos($str, $needles[$i], $pos+1); if ($newPos===false) $needles = substr($needles,0,$i) . substr($needles,$i+1); else $bestNewPos = min($bestNewPos,$newPos); } if (($pos=$bestNewPos)==$size) return -1; } return $reverse ? $size-1-$pos : $pos; } Csaba Gabor from Vienna http://php.net/manual/en/function.strpos.php

« previous php.notes (#154868) next »