note 96525 modified in function.strpos by danbrown

From: Date: Wed, 03 Mar 2010 17:08:48 +0000
Subject: note 96525 modified in function.strpos by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-166583@lists.php.net to get a copy of this message
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 --was-- 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: 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 http://php.net/manual/en/function.strpos.php

« previous php.notes (#166583) next »