PHP 8.4.24 Released!

Voting

: three minus one?
(Example: nine)

The Note You're Voting On

kristin at greenapple dot on dot ca
21 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.

<?php

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

?>

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

<?php

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

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