note 70230 deleted from function.str-replace by felipe

From: Date: Sun, 06 Jan 2008 12:47:55 +0000
Subject: note 70230 deleted from function.str-replace by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-134874@lists.php.net to get a copy of this message
Note Submitter: ahmad at infinity-medias dot com ---- an enhanced version of Dmitry Fedotov's function that can handle arrays as input and output arguments ... <? $string = "test1 test2 test3 test4"; echo str_replace_once('test', 'testing', $string); // testing1 test2 test3 test4 $string = ".NET sucks, Java sucks, PHP sucks"; // that doesn't sound right ... lets fix it! echo str_replace_once("sucks", array("is stupid", "is ugly", "rules"), $string); // .NET is is stupid, Java is ugly, PHP rules function str_replace_once($search, $replace, $subject, &$offset = 0) { if (is_array($search)) { if (is_array($replace)) { foreach ($search as $x => $value) $subject = str_replace_once($value, $replace[$x], $subject, $offset); } else { foreach ($search as $value) $subject = str_replace_once($value, $replace, $subject, $offset); } } else { if (is_array($replace)) { foreach ($replace as $value) $subject = str_replace_once($search, $value, $subject, $offset); } else { $pos = strpos($subject, $search, $offset); if ($pos !== false) { $offset = $pos+strlen($search); $subject = substr($subject, 0, $pos) . $replace . substr($subject, $offset); } } } return $subject; } ?>

« previous php.notes (#134874) next »