php var 转换为年份和月份

BRA*_*AVO 4 php date

$date ='20101015';
Run Code Online (Sandbox Code Playgroud)

如何转换为 $year = 2010, $month = 10,$day =15

谢谢

cod*_*ict 5

您可以将 PHP 子字符串函数用作substr:

$year  = substr($date,0,4);  # extract 4 char starting at position 0.
$month = substr($date,4,2);  # extract 2 char starting at position 4.
$day   = substr($date,6);    # extract all char starting at position 6 till end.
Run Code Online (Sandbox Code Playgroud)

如果您的原始字符串作为前导或尾随空格,这将失败,因此最好将substr修剪后的输入作为。因此,在致电之前,substr您可以执行以下操作:

$date = trim($date);
Run Code Online (Sandbox Code Playgroud)