带有关联数组的str_replace()

Qia*_*iao 23 php

您可以将数组与str_replace()一起使用:

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

$text = str_replace ($array_from, $array_to, $text);
Run Code Online (Sandbox Code Playgroud)

但是如果你有关联数组怎么办?

$array_from_to = array (
 'from1' => 'to1';
 'from2' => 'to2';
);
Run Code Online (Sandbox Code Playgroud)

你如何在str_replace()中使用它?
速度很重要 - 阵列足够大.

Mat*_*hew 46

$text = strtr($text, $array_from_to)

顺便说一下,这仍然是一维的"阵列".

  • `strtr`适用于长度与搜索值不同的替换值.它和`str_replace`之间的区别在于`strtr`只会进行一次翻译(最长的是先匹配),这会更快(但结果不同).例如,['ab'=>'c','c'=>'d']会将'ab'翻译为'c',而使用str_replace则会变为'd'. (4认同)

mau*_*ris 29

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

$text = str_replace(array_keys($array_from_to), $array_from_to, $text);
Run Code Online (Sandbox Code Playgroud)

to字段将忽略数组中的键.这里的关键功能是array_keys.


Rah*_*dav 5

$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
Run Code Online (Sandbox Code Playgroud)