Skip to content

Instantly share code, notes, and snippets.

@meeech
Created October 13, 2010 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meeech/624283 to your computer and use it in GitHub Desktop.
Save meeech/624283 to your computer and use it in GitHub Desktop.
<?php
/**
* Find the index position of the nth occurrence of a string
*
* @param string $haystack Frag we looking for
* @param string $needle Frag we looking for
* @param int $nth
* @return false/int false on not found, else int of strpos
**/
function find_nth($haystack, $needle, $nth ) {
preg_match_all("/{$needle}/",$haystack,$capture,PREG_OFFSET_CAPTURE);
if(isset($capture[0]) && isset($capture[0][ $nth-1 ])) {
return $capture[0][ $nth-1 ][1];
}
return false;
}
$result = find_nth('this is a test string is a', 'is', 4);
if($result !== false) {
echo "Postion: ".$result;
} else {
echo "No luck. There aren't that many instances in the haystack.";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment