duandeng2011 2018-09-29 13:02
浏览 19
已采纳

too long

This question already has an answer here:

I have a regex, which is: /[0-9]+(,[0-9]+)*/.

It accepts only numbers, separated by a comma. For instance:

1,2,3,4 = good
,1,2,3,4 = bad
1,2,3,4, = bad
String = bad

But it also accepts a numbers with a space:

1, 2, 3, 4 = good

How to make regex that wouldn't allow to do so and would only let to enter a numbers, separated by a comma without spaces?

</div>
  • 写回答

3条回答 默认 最新

  • drozwmi5440 2018-09-29 13:29
    关注

    Your regex is correct as is, you just need to use anchors so you check the full string, and not a partial match.

    ^[0-9]+(,[0-9]+)*$
    

    https://regex101.com/r/zU22VX/1/

    An alternative approach could be:

    $string = '1,2,3,4';
    $array = str_getcsv($string);
    foreach($array as $number) {
        if(!is_numeric($number)) {
            echo 'Bad value' . $number;
            break;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 python变量和列表之间的相互影响
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)