-
-
Save fatihtoprak/33c708bd9c2fec73526e to your computer and use it in GitHub Desktop.
PHP : strpos recursive function
This file contains hidden or 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 | |
$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.'"'; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment