PHP regex for any digits followed by specific characters afterwards

Viewed 47

I'm looking to validate a string that has any number of digits followed by a specific character, for example:

"1w 3d 5h 3m" and "32d 5h 3m"

I'm using the following regex at the moment: /\d+[wdhm]\z/ but this is not working if a string contains a letter that I don't want, for example:

"3pp 2h 35m" and "2d 5qq 3m"

The only allowed letters in the string can be "w", "d", "h" and "m" and must be in that order if once is present, for example "2d 35m" is acceptable but "3h 1w" is not because it's in the wrong order.

1 Answers

You may use this regex with multiple optional matches and a lookahead:

^(?=\d)(?:\d+w\h*)?(?:\d+d\h*)?(?:\d+h\h*)?(?:\d+m)?$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?=\d): Lookahead to assert presence of a digit to disallow empty matches
  • (?:\d+w\h*)?: Match 1+ digits followed by w and 0+ whitespaces
  • (?:\d+d\h*)?: Match 1+ digits followed by d and 0+ whitespaces
  • (?:\d+h\h*)?: Match 1+ digits followed by h and 0+ whitespaces
  • (?:\d+m)?: Match 1+ digits followed by m
  • $: End

If you don't want to allow zero spacing between components then use:

^(?=\d)(?:\d+w\h*)?(?:\b\d+d\h*)?(?:\b\d+h\h*)?(?:\b\d+m)?$

RegEx Demo 2

If you want to allow only single spacing then use:

^(?=\d)(?:\d+w\h)?(?:\b\d+d\h)?(?:\b\d+h\h)?(?:\b\d+m)?$

RegEx Demo 3

Related