Rick
Rick

Reputation: 441

preg_match for several patterns

I'm writing an app in PHP that needs to test a field for a proper voucher code. The voucher entry can be in one of three patterns. I'm no good at expressions, so was hoping for a little help from some of the experts here.

The three patterns are: 1000150000 (any 10 digits) 12345678 (any 8 digits) 3JFK-TAB-CDEFG (First spot a number, the rest alpha. With or without hyphens)

I'm thinking, because the three voucher entries are so different, it might have to be done in three different IF statements.

Thanks for any/all help!!! Rick

Upvotes: 0

Views: 105

Answers (4)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can use this:

/^[0-9](?:[0-9]{7}(?:[0-9]{2})?|[A-Z]*(?>-[A-Z]+)*)$/

The main interests of this pattern are:

  • to avoid strings like this: 9ABCD-EFGH- (that finishs with an hyphen)
  • to not retry all the digits by making the 2 last digits optional. (instead of using an alternation)
  • to try to match the first digit only once. (the pattern fails immediatly if the first character is not a digit.)

Upvotes: 0

Bryan Elliott
Bryan Elliott

Reputation: 4095

You could do this:

(^\d{10}$|^\d{8}$|^\d[A-Za-z-]+$)

Working regex example:

http://regex101.com/r/uI9dU0

Upvotes: 4

Michelle Welcks
Michelle Welcks

Reputation: 3904

(\d{10})?(\d{8})?(\d[a-zA-Z-]+)?

This creates three optional groups, 1-3, that will capture any 10 digits (group 1), any 8 digits (group 2), or a number followed by alpha characters, with or without hyphens (group 3).

Here is a link to the expression on regex101.

Upvotes: 0

Michael Lorton
Michael Lorton

Reputation: 44386

Or you could use alternation. That is, write the three regexs and string them together with the | sign meaning "Match one of this".

So

/[^...$]|\d|Z$/

(I.e. three characters or contains a number or ends with Z.)

Upvotes: -1

Related Questions