note 84944 added to function.str-replace
| From: | max at efoxdesigns dot com | Date: | Wed, 06 Aug 2008 19:28:21 +0000 |
| Subject: | note 84944 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-143240@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 208.69.120.35
Probable Submitter: 69.145.86.254
----
Manual Page -- http://www.php.net/manual/en/function.str-replace.php
Edit -- https://master.php.net/note/edit/84944
Del: integrated -- https://master.php.net/note/delete/84944/integrated
Del: useless -- https://master.php.net/note/delete/84944/useless
Del: bad code -- https://master.php.net/note/delete/84944/bad+code
Del: spam -- https://master.php.net/note/delete/84944/spam
Del: non-english -- https://master.php.net/note/delete/84944/non-english
Del: in docs -- https://master.php.net/note/delete/84944/in+docs
Del: other reasons-- https://master.php.net/note/delete/84944
Reject -- https://master.php.net/note/reject/84944
Search -- https://master.php.net/manage/user-notes.php