PHP Regular Expression matching instance code of date and time (timestamp conversion), php instance
Let's start with a simple and practical code.
Date YYYY-MM-DD
$str = '';$isMatched = preg_match('/^\d{4}(\-|\/|.)\d{1,2}\1\d{1,2}$/', $str, $matches);var_dump($isMatched, $matches);
Php requires a certain time format to be converted into a timestamp (indicating the total number of seconds since January 1, and 00 seconds). This requires php Regular Expression judgment, the following code is used:
<? Php // If the matching time is in the format of or 23:59:59, if the front is 0, you can leave $ time = "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) {echo $ timestro = strtotime ($ time) ;}else {echo" error ";}?>
Analysis of this regular expression:
/^ \ 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 end of the expression start character./is the end character of the expression.
^ Start of the string, that is, start ***
$ Indicates the end of the string, that is, the end ***
| Represents or
() Indicates a unit.
D {4} matches a 4-digit number,
(\-) Matches,
(0? [1-9] | 1 [012]) Match month,
(0? [1-9] | [12] [0-9] | 3 [01]) matching day,
(\ 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 entire matching time, minute, and second part ,? Indicates either or not.
The last step is to convert the timestamp of the matched parts.
Current Conversion Result: 1329407999
Attach the example I wrote, the Code is as follows:
<Meta charset = 'utf-8'> <pre> <? Php $ str = "2010/07/08 12:31:56 Haha 13:21:45"; $ str2 =" 2010-07-08 12:31:56 Haha 13:21:45 "; // match only the date preg_match_all ("/d {4}/d {2}/d {2}/", $ str, $ arr ); preg_match_all ("/d {4}-d {2}-d {2}/", $ str2, $ arr2 ); // match the 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 '<font color =" red "> matching date </font> <br> '; print_r ($ Arr); print_r ($ arr2); echo '<font color = "red"> matching date and time </font> <br>'; print_r ($ arr3 ); print_r ($ arr4);?> </Pre>
The above is the regular content about php Date and time. Of course, many of them are verified by frontend js. You can refer to other articles of the customer's home.