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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀