note 100871 modified in function.str-replace by danbrown
| From: | danbrown@php.net | Date: | Fri, 12 Nov 2010 12:13:52 +0000 |
| Subject: | note 100871 modified in function.str-replace by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-173971@lists.php.net to get a copy of this message | ||
A faster way to replace the strings in multidimensional array is to json_encode() it, do the
str_replace() and then json_decode() it, like this:
<?php
function str_replace_json($search, $replace, $subject){
return json_decode(str_replace($search, $replace, json_encode($subject)));
}
?>
This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method,
and 10x simpler in coding.
Compared to:
<?php
function str_replace_deep($search, $replace, $subject)
{
if (is_array($subject))
{
foreach($subject as &$oneSubject)
$oneSubject = str_replace_deep($search, $replace, $oneSubject);
unset($oneSubject);
return $subject;
} else {
return str_replace($search, $replace, $subject);
}
}
?>
--was--
A faster way to replace the strings in multidimensional array is to json_encode() it, do the
str_replace() and then json_decode() it, like this:
function str_replace_json($search, $replace, $subject){
return json_decode(str_replace($search, $replace, json_encode($subject)));
}
This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method,
and 10x simpler in coding.
Compared to:
function str_replace_deep($search, $replace, $subject)
{
if (is_array($subject))
{
foreach($subject as &$oneSubject)
$oneSubject = str_replace_deep($search, $replace, $oneSubject);
unset($oneSubject);
return $subject;
} else {
return str_replace($search, $replace, $subject);
}
}
http://php.net/manual/en/function.str-replace.php