note 38505 added to function.str-replace

From: Date: Wed, 24 Dec 2003 17:15:08 +0000
Subject: note 38505 added to function.str-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-62427@lists.php.net to get a copy of this message
If both the search and replace params are arrays, str_replace() will apply the substitutions incrementally, it is, it will try the first substitution, then the second using the result from the first one, and so on. It may be OK, or it may also be a big problem if you only want to change the original text. For example, consider this code: $search = array("one", "two", "three"); $replace = array("two", "three", "one"); $subject = "one two three"; str_replace() replaces incrementally: echo str_replace($search, $replace, $subject). "<br>"; // echoes "one one one" This function makes the substitutions only to the original text. /** * same as str_replace (array, array, string), but changing only the text in the * original string * $search and $replace are arrays of strings, $subject is a string */ function str_replace_clean ($search, $replace, $subject) { if (!is_array($search) or !is_array($replace) or !is_string($subject)) return $subject; while (count($search)) { // get current terms, reduce the arrays for the next iteration $search_text = array_shift($search); $replace_text = array_shift($replace); // check if the substring is present $pos = strpos($subject, $search_text); if (is_int($pos)) { // match found - break in pieces $pieces = explode($search_text, $subject); if (count($search)) { // only if there are more substitutions to do // make next substitutions in every piece of text between matches foreach ($pieces as $k => $v) { if (strlen($v)) $pieces[$k] = str_replace_clean($search, $replace, $v); } } $subject = join($replace_text, $pieces); break; } } return $subject; } To test: echo str_replace_clean($search, $replace, $subject); // echoes "two three one" -- Xavier ---- Manual Page -- http://www.php.net/manual/en/function.str-replace.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+38505 Delete -- http://master.php.net/manage/user-notes.php?action=delete+38505&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+38505&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#62427) next »