note 97525 deleted from function.str-replace by visualmind
| From: | visualmind@php.net | Date: | Sat, 24 Apr 2010 08:18:56 +0000 |
| Subject: | note 97525 deleted from function.str-replace by visualmind | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-168588@lists.php.net to get a copy of this message | ||
Note Submitter: pjcdawkins at googlemail dot com
----
Here's a deep replace function allowing multi-dimensional arrays in $search, $replace and
$subject. The keys and other structure of $subject are preserved.
<?php
// Auxiliary function:
function _replaceWithAnything($search,$replace,$subject){
if(!is_array($search) || !is_array($replace)){
$search=array($search);
$replace=array($replace);
}
$match=array_search($subject,$search,true);
if($match!==false && array_key_exists($match,$replace))
$subject=$replace[$match];
return $subject;
}
// Main function:
function deepReplace($search,$replace,$subject){
if(!is_array($subject))
return _replaceWithAnything($search,$replace,$subject);
foreach($subject as &$val){
if(is_array($val)){
$val=deepReplace($search,$replace,$val);
continue;
}
$val=_replaceWithAnything($search,$replace,$val);
}
return $subject;
}
?>