PHP regular expression preg_match () issue in timestamps

Regex facing

2013-05-29 15:15:12 string I match /^(\d{4})-(\d{2})-(\d{2})({\s}+(\d{2}):(\d{2}):(\d{2}))?$/ s preg_match , but I don’t check ... its provision is false .

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

+4
source share
2 answers

Let's take a look at your regular expression first. Between the date and time when you match {\s}+ . This means "the symbol { followed by a space / tab followed by one or more } ".

Replace {\s} with ?:\s+ (non-capturing group matching one or more spaces / tabs), therefore full regex

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

Demo

+5
source

Invalid {\s}+ . It should be \s+ . Curly braces are used only as quantifiers or literals.

+2
source

Source: https://habr.com/ru/post/1483290/


All Articles