Created
October 13, 2010 15:35
-
-
Save meeech/624283 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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