alhoseany
alhoseany

Reputation: 771

Need a regular expression to substitute left for right and right for left

I have some css files that i need to use in RTL direction template. I need to convert all left to right and all right to left in these css files using php and regular expression.

For example: when it says "margin-left", it should be "margin-right" and vice versa.

Upvotes: 2

Views: 342

Answers (2)

The simpler way to do it would be to:

$rtl = str_replace('left', '{left}', $css);
$rtl = str_replace('right', '{right}', $rtl);
$rtl = str_replace(array('{left}', '{right}'), array('right', 'left'), $rtl);

The bigger problem are these kinds of css:

margin: 0 5px 0 10px;

More bigger problem:

box-shadow: inset 3px 4px 32px black, 2px 3px 2px white

You should clarify on what kind of CSS might occur. I don't think you want to write a full fledged CSS parser

EDIT: I replaced the -left to simply left and the same with right to also support the position: absolute positioning values.

Upvotes: 4

dan-lee
dan-lee

Reputation: 14502

This should to the trick

preg_replace_callback('/(.+)\-(left|right)/i', function($match) { return $match[1].'-'.($match[2] == 'left' ? 'right' : 'left'); }, $str);

Upvotes: 1

Related Questions