Marco Aurélio Deleu
Marco Aurélio Deleu

Reputation: 4367

PHP Regex basic rules - How to specify more than one thing

I'm totally new at the Regex world and here's what I'm trying to accomplish:

[2 Chars] + [Any Amount of Digits] + [/] + [4 Digits]

For Instance:

AB001/2013
XY999537/2014
OB22/2010

Basically all I have is:

preg_match('/\b[A-Z]{2}\b/', $var);

This ensures me that I'll have only 2 characters at the beginning, but I can't seem to figure out how to make the Regex understand that now I want to add another pattern from the 3rd character of the string and forward.

What I've tried:

preg_match('/\b[A-Z]{2}\b[0-9]/', $var);
preg_match('/\b[A-Z]{2}\b\d/', $var);
preg_match('/(\b[A-Z]{2}\b)([0-9])/', $var);

And I don't understand what's wrong.

Upvotes: 0

Views: 49

Answers (2)

anubhava
anubhava

Reputation: 785406

You can use this regex:

'#^[A-Z]{2}[0-9]*/[0-9]{4}$#'

Upvotes: 0

zessx
zessx

Reputation: 68810

This regex should fit your needs :

preg_match('/\b[A-Z]{2}\d+\/\d{4}\b/', $var);
/*
    \b           # word boundary
    [A-Z]{2}     # 2 uppercase letters
    \d+          # 1+ digits (\d = [0-9])
    \/           # a slash (escaped)
    \d{4}        # 4 digits
    \b           # word boundary
*/

enter image description here

Upvotes: 3

Related Questions