Search code examples
phpregexregular-language

Move multiple letters in string using regex


Using a regular expression I want to move two letters in a string.

W28
L36
W29-L32

Should be changed to:

28W
36L
29W-32L

The numbers vary between 25 and 44. The letters that need to be moved are always "W" and/or "L" and the "W" is always first when they both exist in the string. I need to do this with a single regular expression using PHP. Any ideas would be awesome!

EDIT: I'm new to regular expressions and tried a lot of things without success. The closest I came was using "/\b(W34)\b/" for each possibility. I also found something about using variables in the replace function but had no luck using these.


Solution

  • Your regex \b(W34)\b matches exactly W34 as a whole word. You need a character class to match W or L, and some alternatives to match the numeric range, and use the most of capturing groups.

    You can use the following regex replacement:

    $re = '/\b([WL])(2[5-9]|3[0-9]|4[0-4])\b/'; 
    $str = "W28\nL36\nW29-L32"; 
    $result = preg_replace($re, "$2$1", $str);
    echo $result;
    

    See IDEONE demo

    Here, ([WL]) matches and captures either W or L into group 1, and (2[5-9]|3[0-9]|4[0-4]) matches integer numbers from 25 till 44 and captures into group 2. Backreferences are used to reverse the order of the groups in the replacement string.

    And here is a regex demo in case you want to adjust it later.