frosty
frosty

Reputation: 2669

Replacing all words at the same time

I'm trying to replace all words at the same time using str_replace(), but I'm not sure how to do it. Basically, I need change you to me and me to you at the same time. How would I do that?

<?php

$string = "you me";
$string = str_replace("you", "me", $string);
$string = str_replace("me", "you", $string);

echo $string;

?>

Result:

you you

Need Result:

me you

Upvotes: 2

Views: 125

Answers (1)

v7d8dpo4
v7d8dpo4

Reputation: 1399

strtr() can accept array of pairs 'from' => 'to' to replace as second argument:

echo strtr($string, array('you' => 'me', 'me' => 'you'));

Upvotes: 1

Related Questions