note 104774 deleted from function.str-replace by cmb
| From: | cmb@php.net | Date: | Sun, 15 Sep 2019 14:51:30 +0000 |
| Subject: | note 104774 deleted from function.str-replace by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212218@lists.php.net to get a copy of this message | ||
Note Submitter: hakre
----
I was looking for a str_replace function supporting callbacks. As I didn't found one I wrote
one my own. Works exactly like str_replace, but the replace parameter is a callback or an array of
callbacks (instead of string/strings in str_replace). The callback function accepts two arguments,
the string that is being replaced and the count of the replacement being done.
<?php
/**
* str_ureplace
*
* str_replace like function with callback
*
* @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;
}
?>