note 82826 added to function.str-replace
| From: | cclarkson at htcomp dot net | Date: | Sun, 27 Apr 2008 22:32:28 +0000 |
| Subject: | note 82826 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-138858@lists.php.net to get a copy of this message | ||
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}.'
);
?>
----
Server IP: 208.69.120.35
Probable Submitter: 71.53.82.237
----
Manual Page -- http://www.php.net/manual/en/function.str-replace.php
Edit -- https://master.php.net/note/edit/82826
Del: integrated -- https://master.php.net/note/delete/82826/integrated
Del: useless -- https://master.php.net/note/delete/82826/useless
Del: bad code -- https://master.php.net/note/delete/82826/bad+code
Del: spam -- https://master.php.net/note/delete/82826/spam
Del: non-english -- https://master.php.net/note/delete/82826/non-english
Del: in docs -- https://master.php.net/note/delete/82826/in+docs
Del: other reasons-- https://master.php.net/note/delete/82826
Reject -- https://master.php.net/note/reject/82826
Search -- https://master.php.net/manage/user-notes.php