1

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

2
  • 3
    This array is not multi-dimensional, BTW. Commented Jul 3, 2011 at 8:33
  • 1
    I think you mean associative array, not multi-dimensional. Commented Jul 3, 2011 at 8:51

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

It replaces from left to right doesnt it ? What i want is just to replace all the matches in the string
Nope, this will replace all the matches in the string.
@kritya Yes, it replaces from left to right. See my edited answer.
Ill try it when i get to home
2
$ar = array("ToFind" => "ToBeReplaced", "ToFind1" => "ToBeReplaced1");
echo str_replace(array_keys($ar), $ar, $subject);

http://php.net/str_replace

3 Comments

It replaces from left to right doesnt it ? What i want is just to replace all the matches in the string
@kritya: What do you mean by It replaces from left to right ? It should replace all occurrences. Have a look at the documentation.
No take a better look at the documentation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.