JohnHoulderUK
JohnHoulderUK

Reputation: 679

Why does type casting from string to integer always return "0"?

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

Answers (3)

Besnik
Besnik

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

Tadeck
Tadeck

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

DaveRandom
DaveRandom

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:

  • If the start of the string is a valid numeric representation, use that until we come across a character incompatible with that format
  • Otherwise return zero

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

Related Questions