2010-03-08 101 views
19

您可以使用str_replace()函数数组:如果你有关联数组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()一起使用?
速度事项 - 阵列足够大。

回答

37

$text = strtr($text, $array_from_to)

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

+0

是的,我的不好。改变了它 – Qiao 2010-03-08 04:37:51

+0

它不是说明问题的完美解决方案(原因长度应该是相同的),但它是在我的情况理想。速度很快。 – Qiao 2010-03-08 04:48:39

+3

'strtr'可以正常使用与搜索值长度不同的替换值。它和'str_replace'的区别在于'strtr'只会做一次翻译(最长的时候会先匹配),这会更快(但结果不同)。例如,['ab'=>'c','c'=>'d']会将'ab'翻译为'c',而使用str_replace时,它将变成'd'。 – Matthew 2010-03-08 04:54:15

1
$keys = array_keys($array); 
$values = array_values($array); 
$text = str_replace($key, $values, $string); 
24
$array_from_to = array (
    'from1' => 'to1', 
    'from2' => 'to2' 
); 

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

to场会忽略你的数组中的键。这里的关键功能是array_keys

+1

哇!这里非常巧妙地使用函数。即使在2014年,这个作品非常漂亮! – arrayown 2014-05-16 05:27:42

+1

谢谢@ user1383815 - 时间过得真快:这种感觉后只是远距传送。 – mauris 2014-05-16 16:17:21

+0

能$ array_from_to在不同的顺序比array_keys遍历()返回? – PhoneixS 2018-02-02 10:57:48

2
$search = array('{user}', '{site}'); 
$replace = array('Qiao', 'stackoverflow'); 
$subject = 'Hello {user}, welcome to {site}.'; 

echo str_replace ($search, $replace, $subject); 

结果在Hello Qiao, welcome to stackoverflow.

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

这不是一个二维数组,它是一个关联数组。

扩展在第一个例子,我们的$搜索作为数组的键和$更换,因为它的价值,代码是这样的。

$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); 

结果在Hello Qiao, welcome to stackoverflow.

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