Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace() with associative array

Tags:

php

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.

like image 903
Qiao Avatar asked Mar 08 '10 04:03

Qiao


5 Answers

$text = strtr($text, $array_from_to)

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

like image 163
Matthew Avatar answered Oct 04 '22 23:10

Matthew


$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.

like image 45
mauris Avatar answered Oct 04 '22 23:10

mauris


$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
like image 29
Rahul Yadav Avatar answered Oct 05 '22 01:10

Rahul Yadav


$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..

like image 23
Mark Tomlin Avatar answered Oct 04 '22 23:10

Mark Tomlin


$keys = array_keys($array);
$values = array_values($array);
$text = str_replace($key, $values, $string);
like image 45
Tyler Carter Avatar answered Oct 05 '22 01:10

Tyler Carter