doqpm82240 2014-12-11 15:05
浏览 275
已采纳

当字符串以0开头时,PHP substr

Working on a way to convert the number part of a UK licence plate to that of the reg year.

The aim is to take e.g 55 / 03 / 62

And output how they should be: 2005 / 2003 / 2012

My initial plan was this:

function convertPlateYearToYYYY($vrmYear) {
  $firstDigit = substr($vrmYear, 0, 1);
  $secondDigit = substr($vrmYear, 1, 1);
  if ($firstDigit == 6) {
    $partOne = '1';
  } else {
    $partOne = '0';
  }
$date = "20" . $partOne . $secondDigit;
return $secondDigit;
}

$vrmYear = '05'

echo convertPlateYearToYYYY($vrmYear);

This works fine, but if submitting a value that starts with 0 (like in the example) the substr seems to fail and doesnt return anything. How do I overcome this?

  • 写回答

3条回答 默认 最新

  • doufen1890 2014-12-11 15:13
    关注

    First of all you're using return $secondDigit; when I think you want to do return $date; in your function.

    Without going into further discussion about your question, here's a working solution accessing the first and second digits of your string as an array instead of using substr:

    function convertPlateYearToYYYY($vrmYear) {
        $firstDigit  = $vrmYear[0];
        $secondDigit = $vrmYear[1];
    
        if (6 == $firstDigit) {
            $partOne = '1';
        } else {
            $partOne = '0';
        }
    
        $date = "20{$partOne}{$secondDigit}";
    
        return $date;
    }
    
    $vrmYear = '05';
    
    echo convertPlateYearToYYYY($vrmYear);
    

    Working example in Codepad

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下