Reputation: 3362
I was looking for a way in php which can replace a string like this
<?php
$ar = array(
"ToFind" => "ToBeReplaced",
"ToFind1" => "ToBeReplaced1"
);
?>
and so on ?
Any help ? Thanks
Upvotes: 1
Views: 2570
Reputation: 3536
Simple replacement tasks can be done like this using str_replace
:
$string = str_replace(array_keys($ar), array_values($ar), $string);
As noted in the examples, this may sometimes lead to unexpected behaviour because the replacement is performed left-to-right, ie. the output of the first replacement acts as input for the second replacement and so on. The comments on the PHP manual page for str_replace
contain a lot of ideas for replacing occurrences in the original string. This one, for example, might be close to what you're looking for:
function stro_replace($search, $replace, $subject)
{
return strtr($subject, array_combine($search, $replace));
}
$search = array('ERICA', 'AMERICA');
$replace = array('JON', 'PHP');
$subject = 'MIKE AND ERICA LIKE AMERICA';
echo str_replace($search, $replace, $subject);
// output: "MIKE AND JON LIKE AMJON", which is not correct
echo stro_replace($search, $replace, $subject);
// output: "MIKE AND JON LIKE PHP", which is correct
Upvotes: 2
Reputation: 521995
$ar = array("ToFind" => "ToBeReplaced", "ToFind1" => "ToBeReplaced1");
echo str_replace(array_keys($ar), $ar, $subject);
Upvotes: 2