多字PHP数组替换

时间:2008-12-14 18:06:26

标签: php arrays

<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements[0] = 'slow';
$replacements[1] = 'black';
$replacements[2] = 'bear';
echo preg_replace($patterns, $replacements, $string);
?>

好的伙计们, 现在我有上面的代码。它运作良好。 现在举个例子我想用“慢”代替“懒”和“狗”我现在要做的就是这样,对吧?

<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$patterns[3] = '/lazy/';
$patterns[4] = '/dog/';
$replacements[0] = 'slow';
$replacements[1] = 'black';
$replacements[2] = 'bear';
$replacements[3] = 'slow';
$replacements[4] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>

确定。

所以我的问题是,我有什么方法可以这样做

$patterns[0] = '/quick/', '/lazy/', '/dog/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements[0] = 'slow';
$replacements[1] = 'black';
$replacements[2] = 'bear';

由于

3 个答案:

答案 0 :(得分:2)

为什么不使用str_replace?

$output = str_replace(array('quick', 'brown', 'fox'), array('lazy', 'white', 'rabbit'), $input)

答案 1 :(得分:2)

您可以使用"Alternation"的管道:

$patterns[0] = '/quick|lazy|dog/';

答案 2 :(得分:0)

您也可以像这样分配数组:

$patterns = array('/quick/','/brown/','/fox/','lazy/',/dog/');

当然分配0-4