Skip to content

Instantly share code, notes, and snippets.

@RadTechDad
Created September 3, 2013 11:16
Show Gist options
  • Save RadTechDad/6422553 to your computer and use it in GitHub Desktop.
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.
/**
* 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