Myanmar
Myanmar

Reputation:

multi words PHP arrays replacement

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

Upvotes: 1

Views: 301

Answers (3)

SchizoDuckie
SchizoDuckie

Reputation: 9401

why not use str_replace ?

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

Upvotes: 2

TravisO
TravisO

Reputation: 9540

You could also just assign the array like so:

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

which of course assign 0-4

Upvotes: 0

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

You can use pipes for "Alternation":

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

Upvotes: 2

Related Questions