Reputation: 679
I'm writing an AJAX chat script and I'm integrating a system to parse the time (basically like BBCode). The problem is, when I try casting the time (UNIX timestamp) to an integer for use with date(), it always returns "0". The code I am using to find and replace is below. I've also added a sample of what I'm trying to parse
$out = preg_replace("/\[time\](.*)\[\/time\]/i",date("c",(int)"$1",$out);
Sample:
<b>GtoXic</b>: [time]1342129366[/time]
Upvotes: 1
Views: 1776
Reputation: 6529
What you need is preg_replace_callback with a callback function:
$out = "<b>GtoXic</b>: [time]1342129366[/time]";
$out = preg_replace_callback('/\[time\]([0-9]*)\[\/time\]/i', 'test', $out);
function test($matches)
{
return date("c", (int)$matches[1]);
}
Upvotes: 0
Reputation: 137310
You need to use preg_replace_callback()
.
The reason your script is failing is because (int)"$1"
is in fact 0
(zero), so before it is passed as one of the arguments, it is already converted to zero.
Upvotes: 2
Reputation: 88647
Because what you are actually casting to an integer is the literal string $1
, and converting a string to an integer works in the following way:
In order to get this to work, you would use preg_replace_callback()
:
$output = preg_replace_callback("/#\[time\](.*)\[/time\]#i", function ($matches) {
return date("c", $matches[1]);
}, $input);
The (int)
cast is actually unnecessary, PHP will automatically handle this when you pass the value to a function that expects an integer.
Upvotes: 5