<?php /* входящие данные 24.2.1989 18.12 */ preg_match('/(\d{1,2})\.(\d{1,2})\.?(\d{4})?/', $inputData, $matches); $birthdate = $matches[3] . '-' . $matches[2] . '-' . $matches[1]; 

the condition works, but skips an unlimited number of characters: 18.12,,,,,,,,,,,,,,,,

  • one
    add ^ to the beginning of the regular season, and $ at the end is mymedia
  • @mymedia please answer. Explain why you need to do this. Comments are for clarification, not answers. - ReinRaus
  • It may be interesting how to find the correct dates: ru.stackoverflow.com/a/602838/481 - ReinRaus
  • You should understand that such an expression will allow you to enter the date of the form 45.99.0001 - teran
  • one
    just in case in php there is a function checkdate() - teran

1 answer 1

Add ^ to the beginning of the regular expression, and $ to the end. In this case, it will not allow extraneous characters around the edges of the string.

  • the ^ character matches the beginning of the line
  • the $ character matches the end of the line

At the same time, I would also like to finalize that, if the year is indicated, the full stop would be mandatory. To do this, we will enclose it in an anonymous group, without capturing the string.

The result should be

 preg_match('/^(\d{1,2})\.(\d{1,2})(?:\.(\d{4}))?$/', $inputData, $matches); 
  • OK thanks. It would also be quite cool if there was a coincidence only with valid dates, but this is up to you. The question is not specified. - ReinRaus
  • Here in this case it is easier to check the resulting array $matches - mymedia
  • Maybe :-) I just like to do all this with regular expressions. - ReinRaus
  • To do everything using regular expressions is not the most efficient way, both in terms of speed and convenience of support. Especially, if to consider cases of type on February 29 and April 31. - Aleksei