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条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?