27

I have the following statement which worked fine before PHP 5.3 using the split function:

list($year, $month, $day, $hour, $min, $sec) = split( '[: -]', $post_timestamp );

After upgrading to PHP 5.3, I get the Deprecated warning:

Deprecated: Function split() is deprecated.

I am trying to parse a string with format like:

2010-08-10 23:07:58

into its component parts.

hakre
  • 193,403
  • 52
  • 435
  • 836
morpheous
  • 16,270
  • 32
  • 89
  • 120
  • Related: [PHP split alternative? (May 2010)](http://stackoverflow.com/q/2813241/367456) – hakre Oct 22 '13 at 21:57

4 Answers4

62

I think you want preg_split.

list($year, $month, $day, $hour, $min, $sec) = preg_split('/[: -]/', $post_timestamp);
Brandon Horsley
  • 7,956
  • 1
  • 29
  • 28
7

Just try to replace "split" with "explode" the newer version of PHP and MYSQL accept "explode" instead of "split"

Baqir Sardar
  • 99
  • 1
  • 1
  • 8
    `explode` can't be used in this case because it can be used with only one delimiter symbol. MySQL isn't related to this question at all. – Pavel Strakhov Jun 13 '12 at 19:17
7
$dateTime = new DateTime('2010-08-10 23:07:58');

$year = $dateTime->format('Y');
$month = $dateTime->format('m');

You get the drill... Depending, on what you're going to do with it, using DateTime object might be more convenient than using six separate variables.

Mchl
  • 61,444
  • 9
  • 118
  • 120
4
var_dump(strptime($post_timestamp, '%Y-%m-%d %H:%M:%S'));
zerkms
  • 249,484
  • 69
  • 436
  • 539
  • 2
    +1 I posted preg_split as an answer to the replacement for split, but I would have to agree that if you are parsing a timestamp, you should use functions designed for that with proper handling, etc. – Brandon Horsley Aug 10 '10 at 22:32
  • @Brandon Horsley: the only weird thing of this solution is that year is not absolute, but the years since 1900 :-S so post-processing is needed :-( – zerkms Aug 10 '10 at 22:33
  • @zerkms Well, than use the "datetime"-type and not timestamps. See Mchl's answer. – feeela Jun 13 '12 at 16:42
  • @zerkms That was a reply to your "the only weird thing of this solution is that year is not absolute, but the years since 1900" above. You can pass in user inputs in several formats into the constructor of the PHP DateTime-objects, which are not bound to the 1900-start-year. Example: `new DateTime( '1765-06-13 16:45' )`; you can then use the object methods or the formatted output to access the parts. My fault was, that I thought `strptime` works on a UNIX-timestamp internally, because of that 1900-thingy; but I think that's not true also – I don't know, where this quirk comes from. – feeela Jun 13 '12 at 21:05
  • @feeela: oh, right. Feeling like a jerk now :-S I need to be more attentive then :-S (even in cases the answer was given 1.5y ago). Sorry :-( – zerkms Jun 13 '12 at 21:13
  • @zerkms whoops, I didn't consider the date… ;-) – feeela Jun 13 '12 at 22:21