doupin1073 2019-01-21 19:36
浏览 62
已采纳

PHP - 以2个逗号分隔的整数检查前导0

I have a user-input string with 2 comma-delimited integers.

Example (OK):

3,5

I want to reject any user input that contains leading 0's for either number.

Examples (Bad):

03,5
00005,3
05,003

Now what I could do is separate the two numbers into 2 separate string's and use ltrim on each one, then see if they have changed from before ltrim was executed:

$string = "03,5";

$string_arr = explode(",",$string);

$string_orig1 = $string_arr[0];
$string_orig2 = $string_arr[1];

$string_mod1 = ltrim($string_orig1, '0');
$string_mod2 = ltrim($string_orig2, '0');

if (($string_mod1 !== $string_orig1) || ($string_mod2 !== $string_orig2)){
    // One of them had leading zeros!
}

..but this seems unnecessarily verbose. Is there a cleaner way to do this? Perhaps with preg_match?

  • 写回答

5条回答 默认 最新

  • dongren4147 2019-01-21 20:03
    关注

    All the current answers fail if any of the values are simply 0.

    You can just convert to integer and back and compare the result.

    $arr = explode(',', $input);
    foreach($arr as $item) {
        if( (str)intval($item) !== $item ) {
            oh_noes();
        }
    }
    

    However I am more curious as to why this check matters at all.

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

报告相同问题?

悬赏问题

  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式