如何用PHP date()计算周年并在HTML段落显示带序数后缀的内容
问题
想在HTML段落里动态生成类似「2023是第45周年……」的内容,试了这段代码:
<?php echo date("Y") ?> will see the <?php echo date("Y", strtotime("-1978 year")) ?> anniversary of...
结果返回「2023 will see the 0045 anniversary of...」,需要去掉前导零,还要加上st/nd/rd/th这类序数后缀,问能不能用简单的内联PHP实现,还是得用JavaScript?
解答
完全可以用PHP实现,不需要依赖JavaScript,服务器端处理比前端JS更直接,步骤如下:
1. 解决前导零问题
你之前用date("Y")处理时间偏移得到的是4位年份格式,所以会出现0045。直接用当前年份减去起始年份(1978)更简单,这样得到的就是不带前导零的整数:
$anniversary = date("Y") - 1978;
2. 添加序数后缀
写一段简单的逻辑判断后缀,要考虑11/12/13这类特殊情况(它们不管最后一位都是th),可以直接把逻辑写在内联代码里:
完整内联实现代码
<?php $currentYear = date("Y"); $anniversaryNum = $currentYear - 1978; // 计算序数后缀 $lastDigit = $anniversaryNum % 10; $secondLastDigit = floor($anniversaryNum / 10) % 10; $suffix = $secondLastDigit == 1 ? 'th' : ($lastDigit == 1 ? 'st' : ($lastDigit == 2 ? 'nd' : ($lastDigit == 3 ? 'rd' : 'th'))); // 输出内容 echo "$currentYear will see the {$anniversaryNum}{$suffix} anniversary of..."; ?>
更精简的内联写法(可读性稍弱)
如果想尽量压缩成一行内联代码,也可以这么写:
<?php $y=date("Y");$a=$y-1978;$s=(floor($a/10)%10==1)?'th':(($a%10==1)?'st':(($a%10==2)?'nd':(($a%10==3)?'rd':'th')));echo "$y will see the {$a}{$s} anniversary of..."; ?>
这样生成的内容就是「2023 will see the 45th anniversary of...」,完全符合需求。
内容的提问来源于stack exchange,提问作者Kwaimai
相关产品推荐
相关产品推荐

