Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regular expression issue preg_match() on timestamps

Tags:

regex

php

Facing issue with regular expression

2013-05-29 15:15:12 string I am matching with /^(\d{4})-(\d{2})-(\d{2})({\s}+(\d{2}):(\d{2}):(\d{2}))?$/ with preg_match but not validating ... its giving false.

What should be regexp to match 2013-05-29 15:15:12 or 2013-05-29 pattern.

like image 471
Poonam Bhatt Avatar asked Mar 24 '23 19:03

Poonam Bhatt


2 Answers

Let's take a look at your regex first. Between the date and the time you're matching {\s}+. This means "the character {, followed by a space/tab, followed by one or more }'s".

Replace {\s} with ?:\s+ (a non capturing group matching one or more spaces/tabs) so the full regex is

^(\d{4})-(\d{2})-(\d{2})(?:\s+(\d{2}):(\d{2}):(\d{2}))?$

DEMO

like image 177
h2ooooooo Avatar answered Apr 05 '23 21:04

h2ooooooo


The {\s}+ is wrong. It should be \s+. The curly brackets are used as quantifiers or literals only.

like image 26
slackwing Avatar answered Apr 05 '23 20:04

slackwing