I have a string and I want each YYYY-MM-DD HH:MM:SS
date time string to be replaced with a unix timestamp.
I have managed to get as far as identifying where date time strings occur:
$my_string = 'Hello world 2014-12-25 10:00:00 and foo 2014-09-10 05:00:00, bar';
preg_match_all('((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))',$my_string,$my_matches, PREG_OFFSET_CAPTURE);
print_r($my_matches);
This outputs an array of arrays containing the value of the date time string that was matched and its location:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 2014-12-25 10:00:00
[1] => 12
)
[1] => Array
(
[0] => 2014-09-10 05:00:00
[1] => 40
)
)
)
From this point I was going to loop through the arrays and replace based on str_replace()
and strtotime()
however I'm thinking it would have lower execution time if I could do something like this:
$my_string = preg_replace(
'((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))',
strtotime($VALUE_OF_MATCHED_STRING),
$my_string
);
So that every found instance of the matched would simply be made to strtotime()
format.
What is the correct way to get this result? Is looping the most feasible way?
Use preg_replace_callback()
instead. It allows you to perform a search and replace using a callback function:
echo preg_replace_callback($pattern, function ($m) {
return strtotime($m[0]);
}, $my_string);
$m
is the array containing the matched items. $m[0]
contains the date string.
The above code would output:
Hello world 1419501600 and foo 1410325200, bar
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加