Created
September 14, 2013 06:58
-
-
Save hassanjamal/6559484 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.'"'; | |
} | |
?> |
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
nice strpos_recursive :)