str_replace() with associative array

0 votes
asked Mar 8, 2010 by qiao

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.

5 Answers

0 votes
answered Mar 8, 2010 by tyler-carter
$keys = array_keys($array);
$values = array_values($array);
$text = str_replace($key, $values, $string);
0 votes
answered Mar 8, 2010 by matthew

$text = strtr($text, $array_from_to)

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

0 votes
answered Mar 8, 2010 by mauris
$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. The key function here is array_keys.

0 votes
answered Mar 8, 2010 by mark-tomlin
$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..

0 votes
answered Mar 18, 2016 by rahul-yadav
$text='yadav+RAHUL(from2';

  $array_from_to = array('+' => 'Z1',
                         '-' => 'Z2',
                         '&' => 'Z3',
                         '&&' => 'Z4',
                         '||' => 'Z5',
                         '!' => 'Z6',
                         '(' => 'Z7',
                         ')' => 'Z8',
                         '[' => 'Z9',
                         ']' => 'Zx1',
                         '^' => 'Zx2',
                         '"' => 'Zx3',
                         '*' => 'Zx4',
                         '~' => 'Zx5',
                         '?' => 'Zx6',
                         ':' => 'Zx7',
                         "'" => 'Zx8');

  $text = strtr($text,$array_from_to);

   echo $text;

 //output is

yadavZ1RAHULZ7from2
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...