2

Looking for regex expression (for php) to replace patterns multiple times without affecting remainder. The actual replace required is to reverse certain numbers, 10-1 should be changed to 1-10, i.e. "number1" "dash" "number2" where number is integer (could have more than 1 digit) should be replaced by "number2" "dash" "number1". Note that the pattern does not allow spaces. This pattern can occur any (unknown) number of times including 0.

This text can be surrounded by any other text including numbers, letters, spaces, special characters.

Examples

     asdasdasd10-1 2-3asdasd 9-2 2 3XSSADSD

should be changed to

     asdasdasd1-10 3-2asdasd 2-9 2 3XSSADSD

Similarly

     <asdasd 10 - 2 dfdsfsdfsdf 8-2

changed to

     <asdasd 10 - 2 dfdsfsdfsdf 2-8

1 Answer 1

3

Use this:

$replaced = preg_replace('~(\d+)-(\d+)~', '\2-\1', $yourstring);

In the demo, see the substitutions at the bottom.

Explanation

  • The parentheses around (\d+) captures digits to Group 1
  • We match the -
  • The parentheses around (\d+) captures digits to Group 2
  • \2-\1 replaces with Group 2 + hyphen + Group 1

Reference

Sign up to request clarification or add additional context in comments.

6 Comments

FYI: Added demo and explanation. :)
yeah, thanks for sharing this to us :) It is a good learning tool for Regex beginners.
@0ar.ch IMO the best value is in the articles in the references. :)
Just saw them. Yup! I like the one by Rex :)
@anubhava He doesn't seem to be switching them around in the 10 - 2, just the ones directly in contact like 2-3
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.