Deprecated: Function split() is deprecated. How to rewrite this statement?
Asked Answered
F

4

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.

Fractostratus answered 10/8, 2010 at 22:18 Comment(1)
Related: PHP split alternative? (May 2010)Malita
L
62

I think you want preg_split.

list($year, $month, $day, $hour, $min, $sec) = preg_split('/[: -]/', $post_timestamp);
Libelee answered 10/8, 2010 at 22:24 Comment(0)
S
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.

Supersede answered 10/8, 2010 at 22:24 Comment(0)
T
7

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

Ternate answered 13/6, 2012 at 16:32 Comment(1)
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.Rundle
S
4
var_dump(strptime($post_timestamp, '%Y-%m-%d %H:%M:%S'));
Shirty answered 10/8, 2010 at 22:29 Comment(6)
+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.Libelee
@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 :-(Shirty
@Shirty Well, than use the "datetime"-type and not timestamps. See Mchl's answer.Andromache
@Shirty 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.Andromache
@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 :-(Shirty
@Shirty whoops, I didn't consider the date… ;-)Andromache

© 2022 - 2024 — McMap. All rights reserved.