php - Replace in one step based on matched result -
i have string , want each yyyy-mm-dd hh:mm:ss
date time string replaced unix timestamp.
i have managed far identifying date time strings occur:
$my_string = 'hello world 2014-12-25 10:00:00 , 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 array of arrays containing value of date time string matched , 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 point going loop through arrays , replace based on str_replace()
, strtotime()
i'm thinking have lower execution time if 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 every found instance of matched made strtotime()
format.
what correct way result? looping feasible way?
use preg_replace_callback()
instead. allows perform search , replace using callback function:
echo preg_replace_callback($pattern, function ($m) { return strtotime($m[0]); }, $my_string);
$m
array containing matched items. $m[0]
contains date string.
the above code output:
hello world 1419501600 , foo 1410325200, bar
Comments
Post a Comment