Regular expresson match and replace multiple strings

i need to declate a pattern for each string i want to match. if there way i can match right or left and replace according to that ?
if you found left replace with right, if you found right replace with left acrording to the order in the pattern


$pattern = array('/[^-{]\\bleft\\b/','/[^-{]\\bright\\b/');
$replace = array('right','left');
$subject = 'body {left: 24px;} p {right: 24px;}';
$subject = preg_replace($pattern, $replace, $subject);
echo $subject;

this code doesn’t work.

You will likely need to perform a 3-way replace

First replacing ‘left:’ with ‘new-right:’, then replace ‘right:’ with ‘left:’, and finally replace ‘new-right:’ with ‘right:’

To my knowledge, I can’t think of a way to accomplish what you want to do without a more work. The above approach will allow you to use three preg_replace calls and be done.

thanks you cpradio
but as passing the string and the regex as array can’t do it ?
if i try the regex as standalone it’s working but as array it doesn’t do nothing

Right, I don’t think PHP supports passing arrays to the preg_replace function yet, like they do for other functions

sure it does. preg_replace takes 3 mixed variables; any of the three may be arrays. As per the manual, the behavior is:
“If (the replacement parameter) is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string.”

Ah, which is why it wouldn’t work for his given scenario, he wants both replacements to use the same subject value, which you can’t do. Interesting

what he wants wont be doable with arrays because he wants to swap values, and that isnt how array-replacing works.

What he would get out is 2 lefts.

Why? Because it would be an iterative replacement.

Replace all lefts with rights.
Replace all rights with lefts.
Result: 2 lefts.

Now, you could do it with two preg_replace’s; one with an array pattern replacement; the second which undoes the go-between step;

something like:
preg_replace(array(‘left’,‘right’),array(‘notavalue’,‘left’),$subject);
preg_replace(‘notavalue’,‘right’,$subject);

Alternately : $subject = preg_replace_callback(‘/(left)|(right)/’, function($match) { return ($match[0] == ‘left’) ? ‘right’ : ‘left’; }, $subject);

Maybe I’m wrong, but I took your prior post to mean that since $subject isn’t an array, the second iteration would use an empty string and not the updated subject from the first pass, which means, this method won’t work. You really would have to have 3 separate preg_replace calls. I haven’t had time to test this theory, but that is how I read the information you posted.

That one is neat! I like it!