note 84944 deleted from function.str-replace by philip

From: Date: Wed, 07 Oct 2009 08:00:25 +0000
Subject: note 84944 deleted from function.str-replace by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161452@lists.php.net to get a copy of this message
Note Submitter: max at efoxdesigns dot com ---- Sorry, folks. That last note I put up won't work quite correctly. Unlike str_replace(), that snippet I showed you will replace any characters that aren't in your $search array with an empty string. To correct this behavior, add this check to the foreach loop: <?php //... if (!empty($i[0])) $subject .= $replace[$i[0]]; else $subject .= $nchar; //now, if the search character isn't found (ie, we don't care about it), it will stay the same, instead of getting replaced by an empty string. ?> The whole thing would look like the following, if you were to put it into a function: <?php function char_replace_once($search, $replace, $subject) { $newArr = str_split($subject); $subject = ''; foreach ($newArr as $nchar) { $i = array_keys($search, $nchar); if (!empty($i[0])) $subject .= $replace[$i[0]]; else $subject .= $nchar; } return $subject; } ?> I'm sure it may not be as efficient as str_replace(), but it successfully replaces characters, correctly. ONE OTHER IMPORTANT THING TO NOTE: Unlike I said before, this will only work for character replacement - not string replacement. The reason, of course, is that the original string gets split into an array, who's members are only one character. Sorry about that. That drawback aside, though, this is still a useful function for doing complete, accurate character replacement.

« previous php.notes (#161452) next »