Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The first problem is your regular expression. You have <code>[^-{]</code> that means that you are checking for a string that DOES NOT start with a <code>-</code> or a <code>{</code> but since <code>{left:</code> starts with a <code>{</code> the match is ignoring it. I imagine what you're trying to say is only replace the word <code>left</code>. To replace only part of a string you need to use back references like this:</p> <pre><code>$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; </code></pre> <p>Notice the parentheses in the <code>$pattern</code>. That is grouping those parts together. Also notice the <code>$n</code> in the <code>$replace</code>. The first parenthesis group <code>([-{]\b)</code> is <code>$1</code>, the second <code>(left)</code> is <code>$2</code>, and the third <code>(\b)</code> is <code>$3</code>.</p> <p>Now that solves replacing the left -> right but you can't do the array as suggested because this will happen:</p> <pre><code>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;} </code></pre> <p>Oops! now you have all left's. That's not very helpful. What you really want is <code>preg_replace_callback</code>. <code>preg_replace_callback</code> will run a user defined function for each match. So what we do is we find all the lefts and rights in one go and then in our function we swap the left/right and return it plus the original string like so:</p> <pre><code>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; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload