0

My problem is I'm trying to validate input submitted on a form as semi-colon delimited coordinates. I only want to accept data that holds the following pattern:

1,2
1,2;3,4
1,2;3,4;5,6

etc.. up to any length of coordinates.

It should fail where the semi-colon or comma is in the wrong place...

e.g. 1;2;3,4

I'm pretty new to both regex and PHP. I used regex101.com to come up with something what I have been trying is:

if (!preg_match('/(\d+,\d+;)*\d+,\d+/', $coordinateData)) {
    return;
}

This matches my pattern but it also matches when the semicolon is in the wrong place.

I would really appreciate help.

clair3st
  • 109
  • 5

1 Answers1

3

Code

See regex in use here

^(\d+,\d+)(?:;(?1))*$

It's pretty much the same as ^\d+,\d+(?:;\d+,\d+)*$ except:

  1. You define the pattern once and reuse it
  2. It's shorter
  3. It's slightly slower (so using ^\d+,\d+(?:;\d+,\d+)*$ may improve performance)

Also, note that placing (?:;\d+,\d+)* at the end improves performance (as opposed to at the start like you have it).


Explanation

  • ^ Assert position at the start of the line
  • (\d+,\d+) Capture the following into capture group 1
    • \d+ Match one or more digits
    • , Match this literally
    • \d+ Match one or more digits
  • (?:;(?1))* Match the following any number of times
    • ; Match this literally
    • (?1) Recurse the first subpattern (contents of capture group 1)
  • $ Assert position at the end of the line
ctwheels
  • 21,901
  • 9
  • 42
  • 77