str_replace() 与关联数组

php
2022-08-30 13:47:21

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

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

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

但是,如果您有关联数组呢?

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

如何将其与 str_replace() 一起使用?
速度很重要 - 阵列足够大。


答案 1

$text = strtr($text, $array_from_to)

顺便说一句,这仍然是一个一维的“数组”。


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

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

该字段将忽略数组中的键。这里的关键功能是 。toarray_keys


推荐