Searches for regex to find and reorder strings

I am looking for a regular expression to find the CSS label template template top-right-bottom-left (i.e.: 10px 20px 40px 0) and replace item 2 with position number 4 (swap left and right). preferably, this regular expression should be able to identify the values โ€‹โ€‹of px, as well as% and em, and will take into account that 0 may be present without any identifier.

-1
source share
3 answers

You can use regex as follows:

(\d+(?:px|em|%)?)\s+(\d+(?:px|em|%)?)\s+(\d+(?:px|em|%)?)\s+(\d+(?:px|em|%)?) 

And implement it like this:

 $subject = '10px 20% 40px 0'; $result = preg_replace('/(\d+(?:px|em|%)?)\s+(\d+(?:px|em|%)?)\s+(\d+(?:px|em|%)?)\s+(\d+(?:px|em|%)?)/i', '$1 $4 $3 $2', $subject); echo $result; // Prints: 10px 0 40px 20% 
+1
source
 $string = 'margin: 10px 20px 40px 0; padding: 10px 20px 40px 0;'; $pattern = '/((margin|padding|border)\:)(\s*\S+)(\s+\S+)(\s+\S+)(\s+[^;.]+)/i'; $replacement = '$1$3$6$5$4'; echo preg_replace($pattern, $replacement, $string, -1, $count); 
0
source

You mean something like this:

 (0|\d+(?:px|em|%))\s(0|\d+(?:px|em|%))\s(0|\d+(?:px|em|%))\s(0|\d+(?:px|em|%)) 

and replace with

 $1 $4 $3 $2 

See here at Regexr

Explanation:

This expression consists of 4 capture groups that are equal, so I explain only one.

This is a capture group due to the hte brackets around the expression. The second pair of brackets has ?: After the opening bracket, because of which it is not an exciting group. Its easy to group alternatives, and I don't need the saved partial result.

 (0|\d+(?:px|em|%)) 

This expression matches either 0 or a series of digits ( \d+ ) followed by px , em or % .

These expressions are combined using the space character \s .

0
source

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


All Articles