Skip to content

Instantly share code, notes, and snippets.

@ktomk
Created July 6, 2011 14:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ktomk/1067437 to your computer and use it in GitHub Desktop.
Save ktomk/1067437 to your computer and use it in GitHub Desktop.
str_ureplace - str_replace with callback functions
<?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;
}
@miaadp
Copy link

miaadp commented May 19, 2022

It's really slow , using preg_replace_callback is really faster

@miaadp
Copy link

miaadp commented May 19, 2022

oh , it's to old :D

@ktomk
Copy link
Author

ktomk commented May 19, 2022

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