substr() is not working as expected

谁说我不能喝 提交于 2020-07-03 04:35:21

问题


I am just trying to extract the date's year, month and day separately so that I can use it as per my wish.

I stored the current date in $today and used substr() to extract the strings from it. But I am getting some strange behaviour from what I am doing.

My current code:

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

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

echo $_year . " " . $_month;

The $_year works correctly as expected but the problem arises from $_month, no matter what position I start my substr() the month and day gets paired up with each other.

Can anyone help me solve this issue? It's driving me crazy.


回答1:


You should have a look at substr reference: http://php.net/manual/it/function.substr.php

That function accepts 3 parameters: $length is the length of the string you want to cut starting from $start

string substr ( string $string , int $start [, int $length ] )

In your case, this will work properly:

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



回答2:


This should work for you:

Just explode() your date by a slash and then use a list() to assign the variables.

list($year, $month, $day) = explode("/", $today);



回答3:


Just use:

echo date("Y m");

If you want to have every part of the date in an individual variable, I highly encourage you to use the DateTime class:

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

echo $dt->format('Y m');



回答4:


$today = date("Y/m/d");
$_year = substr($today, 0,4);
$_month = substr($today, 5,7);
$_day = substr($today, 8, 10);
echo $_year." ".$_month;

should be

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



回答5:


You can use it as

$today = date("Y/m/d");
$today = explode("/", $today);
$year = $today[0];
$month = $today[1]; 
$day = $today[2];
echo $year . ' ' . $month .' '. $day; // 2015 05 05



回答6:


substr() doesn't work asyou think
You're thinking of : string substr ( string $string , int $start , int $end )
But it is : string substr ( string $string , int $start , [int $length)

So use substr($today,5,2) for month and substr($today,7,2) for day



来源:https://stackoverflow.com/questions/30051238/substr-is-not-working-as-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!