Created
September 3, 2013 11:16
-
-
Save RadTechDad/6422553 to your computer and use it in GitHub Desktop.
mostr_replace is a multiple-occurrence string replacement function that will traverse through the haystack until it finds the needle.Once the needle is found, it will replace that occurrence of the needle with the first occurrence of the indexed array.
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
/** | |
* mostr_replace is a multiple-occurrence string replacement function | |
* that will traverse through the haystack until it finds the needle. | |
* Once the needle is found, it will replace that occurrence of the | |
* needle with the first occurrence of the indexed array. | |
* | |
* @param string $needle The token to look for | |
* @param string $haystack The string to search | |
* @param array $replacementArray The array to replace each occurrence of the tokens | |
* @param integer $offset How far into the search string to start the search | |
* @return string The final string with all of the tokens replaced | |
*/ | |
function mostr_replace($needle='', $haystack='', $replacementArray=array(), $offset = 0) | |
{ | |
$counter = 0; | |
while (substr_count($haystack, $needle)) { | |
$needle_position = strpos($haystack, $needle, $offset); | |
if ($needle_position + strlen($needle) > strlen($haystack)) { | |
break; | |
} | |
$haystack = substr_replace($haystack, $replacementArray[$counter], $needle_position, strlen($needle)); | |
$offset = $needle_position + strlen($needle); | |
$counter++; | |
} | |
return $haystack; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment