Verbose PHP Array Replacements

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

      

Ok guys, Now I have the code above. It just works well. Now, for example, I would also like to replace "lazy" and "doggy" with "slow". What I need to do now, it looks like this: "

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

      

Ok.

So my question is, is there a way that I can do this

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

      

thank

+1


source to share


3 answers


You can use channels for "Alternation" :



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

      

+2


source


why not use str_replace?



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

      

+2


source


You can also just assign the array like this:

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

      

which of course assign 0-4

0


source







All Articles