Created
July 6, 2011 14:59
-
-
Save ktomk/1067437 to your computer and use it in GitHub Desktop.
str_ureplace - str_replace with callback functions
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 | |
/** | |
* str_ureplace | |
* | |
* str_replace like function with callbacks for replacement(s). | |
* | |
* @param string|array $search | |
* @param callback|array $replace | |
* @param string|array $subject | |
* @param int $replace_count | |
* @return string|array subject with replaces, FALSE on error. | |
*/ | |
function str_ureplace($search, $replace, $subject, &$replace_count = null) { | |
$replace_count = 0; | |
// validate input | |
$search = array_values((array) $search); | |
$searchCount = count($search); | |
if (!$searchCount) { | |
return $subject; | |
} | |
foreach($search as &$v) { | |
$v = (string) $v; | |
} | |
unset($v); | |
$replaceSingle = is_callable($replace); | |
$replace = $replaceSingle ? array($replace) : array_values((array) $replace); | |
foreach($replace as $index=>$callback) { | |
if (!is_callable($callback)) { | |
throw new Exception(sprintf('Unable to use %s (#%d) as a callback', gettype($callback), $index)); | |
} | |
} | |
// search and replace | |
$subjectIsString = is_string($subject); | |
$subject = (array) $subject; | |
foreach($subject as &$haystack) { | |
if (!is_string($haystack)) continue; | |
foreach($search as $key => $needle) { | |
if (!$len = strlen($needle)) | |
continue; | |
$replaceSingle && $key = 0; | |
$pos = 0; | |
while(false !== $pos = strpos($haystack, $needle, $pos)) { | |
$replaceWith = isset($replace[$key]) ? call_user_func($replace[$key], $needle, ++$replace_count) : ''; | |
$haystack = substr_replace($haystack, $replaceWith, $pos, $len); | |
} | |
} | |
} | |
unset($haystack); | |
return $subjectIsString ? reset($subject) : $subject; | |
} |
oh , it's to old :D
yes, 11 years by now. and IIRC this one was in case there is no preg* avail (or too slow?). @miaadp
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's really slow , using preg_replace_callback is really faster