note 82826 deleted from function.str-replace by philip
| From: | philip@php.net | Date: | Wed, 07 Oct 2009 08:02:05 +0000 |
| Subject: | note 82826 deleted from function.str-replace by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-161456@lists.php.net to get a copy of this message | ||
Note Submitter: cclarkson at htcomp dot net
----
The example presented by bladescope at googlemail dot com has a couple of syntax errors. This works:
<?php
$template = "The {color} {object} is in {location}";
$array = array(
'{object}' => 'Ball',
'{color}' => 'Red',
'{location}' => 'The Playground',
);
foreach ($array as $search => $replace) {
$template = str_replace($search, $replace, $template);
}
print $template;
?>
I did not check it for speed or thoroughly test it, but this function seems to do the same thing
more succinctly.
<?php
function template($array, $template) {
return str_replace(
array_keys($array),
array_values($array),
$template
);
}
echo template(
array(
'{color}' => 'red',
'{object}' => 'ball',
'{location}' => 'the playground',
),
'The {color} {object} is in {location}.'
);
?>