note 82563 deleted from function.str-replace by danbrown
| From: | danbrown@php.net | Date: | Sun, 20 Jul 2008 16:15:07 +0000 |
| Subject: | note 82563 deleted from function.str-replace by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142168@lists.php.net to get a copy of this message | ||
Note Submitter: bladescope at googlemail dot com
----
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".
?>