doufei2662 2015-11-15 15:54
浏览 126


Here is my code

    echo preg_match('/salam{1,1}/',$str);

I write in regex one time min and max but I don't know why it prints 1(true),

And one more question:

I would like to accept just exactly 4 digit (no more, no less) now my code is here:

    $num=234567 ;
    echo preg_match('/[0-9]{4,4}/',$num); 

That it is not correct, it also accept 234567 .

  • 写回答

2条回答 默认 最新

  • dt614037527 2015-11-15 15:59

    The problem in both expressions is that you just match somewhere in the text. If you want to make sure that there is nothing before and after what you match with the expression, you need to include the start and end markers there:

    $str = 'salamsalam';
    echo preg_match('/^salam$/', $str);


    $num = 234567;
    echo preg_match('/^[0-9]{4}$/', $num);

    Note that you don’t need to use {min,max} if you want match exactly a specific number of times. Then you can just use {num}. And if you want to match only once, you don’t need to add any specifier.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
  • dongza3124 2015-11-15 15:58


    Your regex is correct in both cases.

    The problem is, preg_match() returns true if there is any match found --- if there is more than one match found, then it will still print true.


    You can add a ^ to match the beginning and a $ to match the end in your regex so that it will match the whole string (or not).




  • ¥15 IDEA构建失败?怎么搞
  • ¥15 求该题的simpson,牛顿科特斯matlab代码,越快越好
  • ¥30 求解,有偿,可商量价格
  • ¥15 编译arm板子的gcc
  • ¥15 C++代码报错问题,c++20协程
  • ¥15 c++图Djikstra算法求最短路径
  • ¥15 Linux操作系统中的,管道通信问题
  • ¥15 ansible tower 卡住
  • ¥15 等间距平面螺旋天线方程式
  • ¥15 通过链接访问,显示514或不是私密连接