samquo
samquo

Reputation: 757

What does this regex or preg_match check

I'm not that familiar with regex. Can someone tell me what this regex is trying to do? Does it return boolean or an array?

$res = preg_match('#^[A-Z]{1}( [0-9]{1,3})?((\.[0-9]{1,3}){0,2})?$#i', $value);

Upvotes: 1

Views: 737

Answers (4)

ocodo
ocodo

Reputation: 30319

A breakdown...

  • ^[A-Z]{1} - from the beginning of the line, match one char from A-Z ... [A-Z]
  • ( [0-9]{1,3})? - subgroup \1 - match one space, then a number [0-9] 1-3 digits long {1,3}, ? make this one optional.
  • ((\.[0-9]{1,3}){0,2})?$ - subgroup \3 (nested in \2) - match literal . then a number [0-9] 1-3 digits long {1,3}, match 0-2 {0,2} of this previous group, and optional due to ?, the $ specifies that this match is done at the end of the line.

  • i - end regex, set ignore case. Which means, for example the first [A-Z] could be [a-z] without any change to the matches.

A few possible samples:

B 472.983.421     ( \1 = " 472" \2 = ".983.421" )

A                 ( \1 = "" \2 = "" )

C 18.1.1          ( \1 = " 18" \2 = ".1.1" )

D 0.0.0           ( \1 = " 0" \2 = ".0.0" )

d 0.0.0           ( \1 = " 0" \2 = ".0.0" ) # works due to the #i option.

And so on.

Upvotes: 4

Spliffster
Spliffster

Reputation: 7239

  • Searches at the beginning of string for one character from A-Z: ^[A-Z]{1}
  • space followed by 1-3 digit, might not be included (? at the end): ( [0-9]{1,3})?
  • followed by a dot and 1-3 digit (repeated 0-2 times), might not be included: ((.[0-9]{1,3}){0,2})?

Upvotes: 1

WebChemist
WebChemist

Reputation: 4411

# start of match string

^ starts with

[A-Z]{1} starts with one uppercase letter

( [0-9]{1,3})? possibly followed by a space and 3 digits

((.[0-9]{1,3}){0,2})? possibly followed by a pattern of dot then 1-3 digits zero, one or two times

$ ends with (ie nothing after previous search critera

# end of match string

i case insensitive search

Upvotes: 1

mfonda
mfonda

Reputation: 8003

preg_match always returns an int (1 if matched, 0 otherwise). If you want an array, it accepts a thrid parameter by reference that will be populated with the results.

Upvotes: 1

Related Questions