note 82563 added to function.str-replace
| From: | bladescope at googlemail dot com | Date: | Wed, 16 Apr 2008 14:07:59 +0000 |
| Subject: | note 82563 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-138374@lists.php.net to get a copy of this message | ||
An easier and safer way to use str_replace with arrays without the risk of order messups is by
creating an array. The title would be the string to search for, and the value would be the value to
replace it with. From there, it's a matter of using a foreach loop. e.g.
<?php
$template = "The {color} {object} is in {location}";
$array = array(
'{object}' => 'Ball';
'{color}' => 'Red';
'{location}' => 'The Playground';
);
foreach ($array as $search=>$replace) {
$string = str_replace($search, $replace, $template);
}
print $string; // Returns "The Red Ball is in The Playground".
?>
----
Server IP: 92.48.100.16
Probable Submitter: 90.202.162.193
----
Manual Page -- http://www.php.net/manual/en/function.str-replace.php
Edit -- https://master.php.net/note/edit/82563
Del: integrated -- https://master.php.net/note/delete/82563/integrated
Del: useless -- https://master.php.net/note/delete/82563/useless
Del: bad code -- https://master.php.net/note/delete/82563/bad+code
Del: spam -- https://master.php.net/note/delete/82563/spam
Del: non-english -- https://master.php.net/note/delete/82563/non-english
Del: in docs -- https://master.php.net/note/delete/82563/in+docs
Del: other reasons-- https://master.php.net/note/delete/82563
Reject -- https://master.php.net/note/reject/82563
Search -- https://master.php.net/manage/user-notes.php