The first problem is your regular expression. You have [^-{] , this means that you are checking a line that does NOT start with - or { , but since {left: starts with { , the match ignores it. I imagine what you're trying to say is replace the word left . To replace only part of the string, you need to use backlinks as follows:
$pattern = '/([-{]\b)(left)(\b)/'; $replace = '$1right$3'; $subject = 'body {left: 24px;} p {right: 24px;}'; $subject = preg_replace($pattern, $replace, $subject); // result: body {right: 24px;} p {right: 24px;} echo $subject;
Note the parentheses in $pattern . It groups these parts together. Also note the $n in $replace . The first group of brackets ([-{]\b) is $1 , the second (left) is $2 , and the third (\b) is $3 .
Now that it is decided to replace the left -> right, but you cannot make the array as suggested, because this will happen:
body {left: 24px;} p {right: 24px;} Step 1: replace left pattern body {right: 24px;} p {right: 24px;} Step 2: replace right pattern body {left: 24px;} p {left: 24px;}
Oops! now you have everything left. This is not very helpful. What you really want is preg_replace_callback . preg_replace_callback will run a user-defined function for each match. So what we do, we find all the left and right at a time, and then in our function we replace the left / right and return it plus the original line as follows:
function replaceLeftRight($matches) { // get the opposite left/right $leftRight = ($matches[2] == 'left') ? 'right' : 'left'; return $matches[1] . $leftRight . $matches[3]; } $pattern = '/([-{]\b)(left|right)(\b)/'; $subject = 'body {left: 24px;} p {right: 24px;}'; $subject = preg_replace_callback($pattern, 'replaceLeftRight', $subject); // result: body {right: 24px;} p {left: 24px;} echo $subject;
source share