tags:

views:

190

answers:

3
<?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 above code. It just works well. Now for example I'd like to also replace "lazy" and "dog" with "slow" What I have to do now is would look like this, right?

<?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 any way I can do like this

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

Thanks

+2  A: 

You can use pipes for "Alternation":

$patterns[0] = '/quick|lazy|dog/';
Jonathan Lonowski
Thanks, The output is exactly what I expect.
A: 

You could also just assign the array like so:

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

which of course assign 0-4

TravisO
+2  A: 

why not use str_replace ?

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