Posted By

mladoux on 09/21/10


Tagged

php search String utility manipulation Jaim Thorn


Versions (?)

get nth occurance of a string by jaimthorn[at]yahoo[dot]com


 / Published in: PHP
 

URL: http://www.php.net/manual/en/function.strpos.php#96576

Jaim Thorn\'s handy iterating string searcher.

  1. /**
  2.  * Returns the position of the $nth occurrence of $needle in $haystack, or false if it doesn't exist, or false when illegal parameters have been supplied.
  3.  *
  4.  * @param string $haystack the string to search in.
  5.  * @param string $needle the string to search for.
  6.  * @param integer $nth the number of the occurrence to look for.
  7.  * @param integer $offset the position in $haystack to start looking for $needle.
  8.  * @return MIXED integer either the position of the $nth occurrence of $needle in $haystack,
  9.  * or boolean false if it can't be found.
  10.  */
  11. function strnpos( $haystack, $needle, $nth, $offset = 0 )
  12. {
  13. if( 1 > $nth || 0 === strlen( $needle ) )
  14. {
  15. return false;
  16. }
  17.  
  18. // $offset is incremented in the call to strpos, so make sure that the first call starts at the right position by initially decrementing $offset.
  19. --$offset;
  20. do
  21. {
  22. $offset = strpos( $haystack, $needle, ++ $offset );
  23. } while( --$nth && false !== $offset );
  24.  
  25. return $offset;
  26. }

Report this snippet  

You need to login to post a comment.