substr()未按预期工作

Nav*_*een 2 php substring date

我只是想提取日期year,monthday单独提交,以便我可以按照我的意愿使用它.

我将当前日期存储在其中$today并用于substr()从中提取字符串.但我从我正在做的事情中得到一些奇怪的行为.

我目前的代码:

$today = date("Y/m/d");

$_year = substr($today, 0,4);
$_month = substr($today, 5,7);
$_day = substr($today, 8, 10);

echo $_year . " " . $_month;
Run Code Online (Sandbox Code Playgroud)

$_year工作正常预期,但问题出现,从$_month不管我开始什么位置我的substr()月份和日期被配对彼此.

任何人都可以帮我解决这个问题吗?这让我疯狂.

Riz*_*123 5

这应该适合你:

只需explode()用斜杠表示日期,然后使用a list()来分配变量.

list($year, $month, $day) = explode("/", $today);
Run Code Online (Sandbox Code Playgroud)


hek*_*mgl 5

只需使用:

echo date("Y m");
Run Code Online (Sandbox Code Playgroud)

如果您希望将日期的每个部分都放在单个变量中,我强烈建议您使用DateTime该类:

$dt = new DateTime();
$year = $dt->format('Y');
$month = $dt->format('m');
$day = $dt->format('d');

echo $dt->format('Y m');
Run Code Online (Sandbox Code Playgroud)


小智 5

你应该看看substr参考:http://php.net/manual/it/function.substr.php

该函数接受3个参数:$length是要从中开始剪切的字符串的长度$start

string substr ( string $string , int $start [, int $length ] )
Run Code Online (Sandbox Code Playgroud)

在您的情况下,这将正常工作:

$today = date("Y/m/d");
$_year = substr($today, 0,4);
$_month = substr($today, 5,2);
$_day = substr($today, 8, 2);
echo $_year." ".$_month;
Run Code Online (Sandbox Code Playgroud)