note 97526 added to function.str-replace
| From: | pjcdawkins at googlemail dot com | Date: | Sat, 24 Apr 2010 00:23:16 +0000 |
| Subject: | note 97526 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-168583@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 94.193.45.0
----
Manual Page -- http://www.php.net/manual/en/function.str-replace.php
Edit -- https://master.php.net/note/edit/97526
Del: integrated -- https://master.php.net/note/delete/97526/integrated
Del: useless -- https://master.php.net/note/delete/97526/useless
Del: bad code -- https://master.php.net/note/delete/97526/bad+code
Del: spam -- https://master.php.net/note/delete/97526/spam
Del: non-english -- https://master.php.net/note/delete/97526/non-english
Del: in docs -- https://master.php.net/note/delete/97526/in+docs
Del: other reasons-- https://master.php.net/note/delete/97526
Reject -- https://master.php.net/note/reject/97526
Search -- https://master.php.net/manage/user-notes.php