开发者

str_replace() with associative array

You can use arrays with str_replace():

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

$text = str_repla开发者_开发技巧ce ($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.


$text = strtr($text, $array_from_to)

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


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


$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


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


$keys = array_keys($array);
$values = array_values($array);
$text = str_replace($key, $values, $string);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜