I'm trying to add 24 hours to every date using preg_replace.
I'm having trouble passing the date to strtotime(). All dates are replaced with 1970.
I tried using strtotime() with time() and preg_replace()
$data = "Hello world Jan 19, 2023 8:06:47am testing Feb 09, 2021 2:06:47pm zooph foobar"; echo preg_replace("/[a-zA-Z]{3} \d{2}, \d{4} [0-9]{1,2}\:\d{2}\:\d{2}[ap]m/", date("F j, Y, g:i a", (strtotime("$0")) 86400),$data);
CodePudding user response:
Your regex pattern is correct, but in order to use a function of the match as the replacement, you need to use preg_replace_callback()
here:
$data = "Hello world Jan 19, 2023 8:06:47am testing Feb 09, 2021 2:06:47pm zooph foobar";
$out = preg_replace_callback(
"/[a-zA-Z]{3} \d{2}, \d{4} [0-9]{1,2}\:\d{2}\:\d{2}[ap]m/",
function($m) {
return date("F j, Y, g:i a", (strtotime($m[0])) 86400);
},
$data
);
echo $out;
This prints:
Hello world January 20, 2023, 8:06 am testing February 10, 2021, 2:06 pm zooph foobar
CodePudding user response:
I think you need to add preg_replace_callback function:
$data = "Hello world Jan 19, 2023 8:06:47am testing Feb 09, 2021 2:06:47pm zooph foobar";
echo preg_replace_callback("/[a-zA-Z]{3} \d{2}, \d{4} [0-9]{1,2}\:\d{2}\:\d{2}[ap]m/", function ($matches) {
return date("F j, Y, g:i a", strtotime($matches[0]) 86400);
}, $data);
Result :
Hello world January 20, 2023, 8:06 am testing February 10, 2021, 2:06 pm zooph foobar