Skip to content

Instantly share code, notes, and snippets.

@hassanjamal
Created September 14, 2013 06:58
Show Gist options
  • Save hassanjamal/6559484 to your computer and use it in GitHub Desktop.
Save hassanjamal/6559484 to your computer and use it in GitHub Desktop.
PHP : strpos recursive function
<?php
$mystring = 'welcome !! we are learning now string function';
$findme = 'learning';
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'"."\n";
echo " and exists at position $pos";
}
?>
<?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);
}
}
?>
<br>
<?php
$search = 'a';
$found = strpos_recursive($mystring, $search);
if($found) {
foreach($found as $pos) {
echo 'Found "'.$search.'" in string "'.$mystring.'" at position <b>'.$pos.'</b><br />';
}
} else {
echo '"'.$search.'" not found in "'.$mystring.'"';
}
?>
@kaerer
Copy link

kaerer commented Apr 29, 2019

On line 23
+1 should be strlen($needle)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment