note 104774 added to function.str-replace

From: Date: Wed, 06 Jul 2011 15:08:31 +0000
Subject: note 104774 added to function.str-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-181294@lists.php.net to get a copy of this message
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; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 79.225.16.104 ---- Manual Page -- http://www.php.net/manual/en/function.str-replace.php Edit -- https://master.php.net/note/edit/104774 Del: integrated -- https://master.php.net/note/delete/104774/integrated Del: useless -- https://master.php.net/note/delete/104774/useless Del: bad code -- https://master.php.net/note/delete/104774/bad+code Del: spam -- https://master.php.net/note/delete/104774/spam Del: non-english -- https://master.php.net/note/delete/104774/non-english Del: in docs -- https://master.php.net/note/delete/104774/in+docs Del: other reasons-- https://master.php.net/note/delete/104774 Reject -- https://master.php.net/note/reject/104774 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#181294) next »