I think you'll find strtr will be easier than str_replace in your case
strtr translates each
character in one string to a
character in another string.
Code: Select all
echo strtr("alphabet", "abc", "xyz"); // xlphxyet
str_replace can replace an array of strings with another string in the second array. To do the same as the above code you'd need
Code: Select all
str_replace(array("a", "b", "c"), array("x", "y", "z"), "alphabet")
PHP extended strtr to be a bit like str_replace. Instead of two strings to replace individual character you can pass an array where the key is a search string and the value is the replacement.
Code: Select all
$array = array("find" => "replace");
$string = "Example how strtr and str_replace can do a find/replace with strings";
echo strtr($string, $array); // Example... do a replace/replace with strings
// or with str_replace:
$find = array_keys($array);
$replace = array_values($array); // you can just use $array, actually
$string = str_replace($find, $replace, $string);
echo $string;
As for why they didn't extend str_replace to use one array instead of two, I don't know.
So basically:
- Replacing one character with another (like a mapping): strtr
- The search/replace strings are in separate arrays: str_replace
- The search/replace strings are in one array like search=>replace: strtr