note 84946 deleted from function.str-replace by philip
| From: | philip@php.net | Date: | Wed, 07 Oct 2009 08:00:21 +0000 |
| Subject: | note 84946 deleted from function.str-replace by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-161451@lists.php.net to get a copy of this message | ||
Note Submitter: max at efoxdesigns dot com
----
I'm sorry. I can't believe it: I messed up again. Something that I forgot is that the
php empty() function considers the number zero (0) as an empty value. Therefore, we need to change
our if statement to the following:
<?php
if ($i[0] !== null) $subject .= $replace[$i[0]];
?>
If we left it how it was, the replace ignores the first element of the arrays. ($array[0])
The reason that I used !empty() before, is that I wasn't sure what array_keys() returns if the
element is not found (null? and empty string?), since both null and the empty string print out the
same and I couldn't find what it returned in this case, in the manual.
The final, working function would look like:
<?php
function str_replace_once($search, $replace, $subject) {
$newArr = str_split($subject);
$subject = '';
foreach ($newArr as $nchar)
{
$i = array_keys($search, $nchar);
if ($i[0] !== null) $subject .= $replace[$i[0]];
else $subject .= $nchar;
}
return $subject;
}
?>