tags:

views:

147

answers:

4

You can use arrays with str_replace():

$array_from = array ('from1', 'from2'); 
$array_to = array ('to1', 'to2');

$text = str_replace ($array_from, $array_to, $text);

But what if you have associative array?

$array_from_to = array (
 'from1' => 'to1';
 'from2' => 'to2';
);

How can you use it with str_replace()?
Speed matters - array is big enough.

A: 
$keys = array_keys($array);
$values = array_values($array);
$text = str_replace($key, $values, $string);
Chacha102
+2  A: 
$array_from_to = array (
    'from1' => 'to1';
    'from2' => 'to2';
);

$text = str_replace (array_keys($array_from_to), $array_from_to, $text);

The to field will ignore the keys in your array. Thus there key function here is array_keys

thephpdeveloper
+4  A: 

$text = strtr($text, $array_from_to)

By the way, that is still a one dimensional "array."

konforce
yep, my bad. changed it
Qiao
it is not perfect solution for stated problem (cause lengths should be the same), but it is ideal in my case. And speed is fast.
Qiao
`strtr` works fine with replacement values that differ in length from the search value. The difference between it and `str_replace` is that `strtr` will only do one translation (the longest is matched first), which will be faster (but with different results). E.g., ['ab' => 'c', 'c' => 'd'] will translate 'ab' to 'c', while with str_replace it will become 'd'.
konforce
A: 
$search = array('{user}', '{site}');
$replace = array('Qiao', 'stackoverflow');
$subject = 'Hello {user}, welcome to {site}.';

echo str_replace ($search, $replace, $subject);

Results in Hello Qiao, welcome to stackoverflow..

$array_from_to = array (
    'from1' => 'to1';
    'from2' => 'to2';
);

This is not a two-dimensional array, it's an associative array.

Expanding on the first example, where we place the $search as the keys of the array, and the $replace as it's values, the code would look like this.

$searchAndReplace = array(
    '{user}' => 'Qiao',
    '{site}' => 'stackoverflow'
);

$search = array_keys($searchAndReplace);
$replace = array_value($searchAndReplace);
# Our subject is the same as our first example.

echo str_replace ($search, $replace, $subject);

Results in Hello Qiao, welcome to stackoverflow..

Mark Tomlin