PHP 8.4.24 Released!

Voting

: min(six, eight)?
(Example: nine)

The Note You're Voting On

martijn at martijnfrazer dot nl
14 years ago
This is a function I wrote to find all occurrences of a string, using strpos recursively.

<?php
function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {                
    $offset = strpos($haystack, $needle, $offset);
    if($offset === false) {
        return $results;            
    } else {
        $results[] = $offset;
        return strpos_recursive($haystack, $needle, ($offset + 1), $results);
    }
}
?>

This is how you use it:

<?php
$string = 'This is some string';
$search = 'a';
$found = strpos_recursive($string, $search);

if($found) {
    foreach($found as $pos) {
        echo 'Found "'.$search.'" in string "'.$string.'" at position <b>'.$pos.'</b><br />';
    }    
} else {
    echo '"'.$search.'" not found in "'.$string.'"';
}
?>

<< Back to user notes page

To Top