Please answer this simple SPAM challenge: six plus one?
(Example: nine)

The Note You're Voting On

kristin at greenapple dot on dot ca
13 years ago
I really searched for a function that would do this as I've seen it in other languages but I couldn't find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point.

strnpos() - Find the nth position of needle in haystack.


function strnpos($haystack, $needle, $occurance, $pos = 0) {
        for (
$i = 1; $i <= $occurance; $i++) {
$pos = strpos($haystack, $needle, $pos) + 1;
$pos - 1;


Example: Give me everything up to the fourth occurance of '/'.


= "/home/username/www/index.php";
$needle = "/";
$root_dir = substr($haystack, 0, strnpos($haystack, $needle, 4));

Returns: /home/username/www

Use this example with the server variable $_SERVER['SCRIPT_NAME'] as the haystack and you can self-discover a document's root directory for the purposes of locating global files automatically!

<< Back to user notes page

To Top