PHP regular extraction date, PHP regular matching date and time (timestamp conversion) instance code

First come a relatively simple and practical code


$str = '';

$isMatched = preg_match('/^\d{4}(\-|\/|.)\d{1,2}\1\d{1,2}$/', $str, $matches);

var_dump($isMatched, $matches);

PHP needs a certain time format to convert it into a timestamp (representing the total number of seconds from 00:00:00 on January 01, 1970 GMT to the present), which requires php regular judgment, the following is Code:

//If the matching time format is 2016-02-16 or 2016-02-16 23:59:59, it can be omitted when the front is 0

$time = "2016-12-14 23:59:59";

$patten = "/^\d{4}[\-](0?[1-9]|1[012])[\-](0?[1-9]|[12][0-9] |3[01])(\s+(0?[0-9]|1[0-9]|2[0-3])\:(0?[0-9]|[1-5][0 -9])\:(0?[0-9]|[1-5][0-9]))?$/";

if (preg_match($patten, $time)) {undefined

echo $timestro = strtotime($time);

} else {undefined

echo "error";



Analysis of this regularity:

/^\d{4}[\-](0?[1-9]|1[012])[\-](0?[1-9]|[12][0-9]|3[01 ])(\s+(0?[0-9]|[12][0-3])\:(0?[0-9]|[1-5][1-9])\:(0? [0-9]|[1-5][1-9]))?$/

/ is the start of the expression and the last / is the end of the expression

^ The beginning of the string, that is, it starts with ***

$ indicates the end of the string, which means the end of ***

| means or

() indicates a unit

d{4} matches a 4-digit number,

(\-) matches a "-" sign,

(0?[1-9]|1[012]) matches the month,

(0?[1-9]|[12][0-9]|3[01]) matches days,

(\s+(0?[0-9]|1[0-9]|2[0-3])\:(0?[0-9]|[1-5][0-9])\: (0?[0-9]|[1-5][0-9]))? The whole matching hour, minute and second part, ? means yes or no.

The last step is to perform timestamp conversion on the part that matches successfully.

The current conversion result is: 1329407999

Attached is an example I wrote myself, the code is as follows:


$str="Hey 2010/07/08 12:31:56 Haha 1999/12/31 13:21:45";

$str2="Hey 2010-07-08 12:31:56 Haha 1999-12-31 13:21:45";

// only match dates

preg_match_all("/d{4}/d{2}/d{2}/", $str, $arr);

preg_match_all("/d{4}-d{2}-d{2}/", $str2, $arr2);

//match date and time

preg_match_all("/d{4}/d{2}/d{2}sd{2}:d{2}:d{2}/", $str, $arr3);

preg_match_all("/d{4}-d{2}-d{2}sd{2}:d{2}:d{2}/", $str2, $arr4);

echo ' match date



echo ' match date and time




The above is the regular content of php date and time, of course, many of them are verified by front-end js. You can refer to other articlesad51e517755f8fd6a7ec83ced4ecfaf3.png

Related: PHP regular extraction date, PHP regular matching date and time (timestamp conversion) instance code