note 96525 deleted from function.strpos by danbrown

From: Date: Tue, 17 May 2011 16:49:47 +0000
Subject: note 96525 deleted from function.strpos by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-179820@lists.php.net to get a copy of this message
Note Submitter: http://restaurants.nl ---- I've seen some awful and even outright bizarre examples for finding the nth occurrence of needle inside haystack starting at a given offset, so here's what I believe is a better one: <?php function strnpos($haystack, $needle, $nth, $offset = 0) { for ($retOffs=$offset-1; ($nth>0)&&($retOffs!==FALSE); $nth--) $retOffs = strpos($haystack, $needle, $retOffs+1); return $retOffs; } echo strnpos("who's your daddy, daddy?", "d", 1); // 11 echo strnpos("who's your daddy, daddy?", "d", 3); // 14 echo strnpos("who's your daddy, daddy?", "d", 2, 14); // 18 echo strnpos("who's your daddy, daddy?", "daddy", 2); // 18 ?> enjoy

« previous php.notes (#179820) next »