Regular expression matching and multiple line replacement

I have it:

$only_left_pattern = '/[^-{]\bleft\b/'; $subject = 'body {left: 24px;}\np {right:30px;}'; $subject = preg_replace($only_left_pattern, 'right', $subject); echo $subject; 

I need to declare a pattern for every line that I want to match. If there is a way, can I fit right or left and replace accordingly? Example (syntax from my head):

 $right_left_pattern = '/[^-{](\bleft\b|\bright\b/)'; // if you found left replace with right, if you found right replace with left // acrording to the order in the pattern $subject = preg_replace($only_left_pattern, right|left, $subject); 

What am I asking if I can do something like my example with PHP or just with regex.

I tried the Dave solution

 $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; 

but it does not work, I did not test regex as an array, and it worked.

+4
source share
1 answer

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; 
+1
source

Source: https://habr.com/ru/post/1435897/


All Articles