note 84943 deleted from function.str-replace by philip

From: Date: Wed, 07 Oct 2009 08:00:29 +0000
Subject: note 84943 deleted from function.str-replace by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161453@lists.php.net to get a copy of this message
Note Submitter: max at efoxdesigns dot com ---- Note that the str_replace() function is recursive. This is not usually a problem, unless you are trying to do a replace in which a character or string occurs in the $search array, after the same character or string occurs in the $replace array. (For instance, imagine doing a global character replace.) To demonstrate, take a look at the folowing: <?php $search = array('q','w','e','r','t','y','u'); $replace = array('z','s','d','e','y','f','g'); $mystring = 'qwertyu'; //Outputs: zsdeffg echo str_replace($search, $replace, $mystring); ?> As you would expect, the q gets replaced by a z, the w by an s, and so on. Everything is correct, except that the t doesn't seem to have been replaced by a y. This is not entirely true, however. What happened is that it did, indeed get replaced by a y, but then on the next pass of the str_replace() function, str_replace() found a y and replaced it with an f. To get this to work as we'd like (every letter in the $search array replaced by the cooresponding spot in the $replace array), we can do something like the following: <?php $search = array('q','w','e','r','t','y','u'); $replace = array('z','s','d','e','y','f','g'); $mystring = 'qwertyu'; //Outputs: zsdeffg (Not what we wanted.) echo str_replace($search, $replace, $mystring); $newArr = str_split($mystring); //split $mystring into an array of characters. For php4, you'll have to create the str_split() function. $newstring = ''; foreach ($newArr as $nchar) { $i = array_keys($replace, $nchar); //get the key(s) in the $search array for the character we're replacing. (we assume it occurs only once.) Returns an array of length, 1. $newstring .= $replace[$i[0]]; //find the character in the $replace array that matches the position of the one we're replacing, and add it to $newstring. } //Outputs: zsdeyfg echo $newstring; ?> This time, as you can see, there is a y in place of the t, which was what we wanted. :) Hope that clears up any confusion for anyone wondering why their strings aren't getting replaced as they'd expect.

« previous php.notes (#161453) next »