<?php

/*
 * Find the nth occurance of a string in another string
 *
 * Paul Gregg <pgregg@pgregg.com>
 * 23 September 2003
 *
 * Open Source Code:   If you use this code on your site for public
 * access (i.e. on the Internet) then you must attribute the author and
 * source web site: http://www.pgregg.com/projects/php/code/strnpos.phps
 *
 */


// Optimal solution
Function strnpos($haystack$needle$nth=1$offset=0) {
  if (
$nth 1$nth 1;
  
$loop1 TRUE;
  while (
$nth 0) {
    
$offset strpos($haystack$needle$loop1 $offset $offset+1);
    if (
$offset === FALSE) break;
    
$nth--;
    
$loop1 FALSE;
  }
  return 
$offset;
}

// Interesting solution without using strpos (without offset capability)
Function strnpos2($haystack$needle$nth=1) {
  if (
$nth 1$nth 1;
  
$arr explode($needle$haystack);
  if (
$nth > (count($arr)-1)) return FALSE;
  
$str implode($needlearray_slice($arr0$nth));
  return 
strlen($str);
}

$hay "Hello find the nth ocurrance of the needle in this string";
$needle "l";

print 
"<br>Finding: '$needle' in '$hay'\n";

$pos=0;
$i=1;
while (
$pos!==FALSE) {
  
$pos strnpos($hay$needle$i);
  if (
$pos !== FALSE) {
    print 
"<br>Occurance $i found at char $pos\n";
  }
  
$i++;
}

?>