dqftyn1717 2014-07-22 14:15
浏览 19
已采纳

检查字符串的不同部分时,preg_match失败了

This preg_match will never work even though I think its the right thing.

I'm trying to check a string so that it's structured as follows

$value = US 01 02 1406034963 .JPG //I've put spaces in. The real one is below.

So:

The first part (US) is alphabets, only two characters from a-z

The second part (01) is a value 00 or 01

The third part (02) is digits 0-9 from 2 - 10 (can be 2 to 10 digits long)

The fourth part (1406034963) is a 10 digit figure, and only 10 digits

The fifth part is .jpg or .jpeg or .png. or .gif

But, my function always returns false. Can you please help?

//
function preset($value) {
    if(preg_match('/^[a-z]{2}[00|01][0-9]{2,10}[0-9]{10}[.jpg|.jpeg|.png.|.gif]$/',$value)) {
        return true;
    } else {
        return false;
    }
}

$value = 'US01021406034963.JPG';

if(preset($value)) {
    echo 'Yeah!';
} else {
    echo 'Boo!';
}
  • 写回答

3条回答 默认 最新

  • dourenzhou8740 2014-07-22 14:18
    关注

    [] denotes a character class. Simply put, a character class is a way of denoting a set of characters in such a way that one character of the set is matched.

    You're trying to use alternation inside character classes. It will not work as you expect it to. For example, the regex [00|01] would match 0, the literal character |, or 1, and not 00 or 01.

    To match either of the set, you can simply use grouping. In this case, you're not going to use the matched text anywhere, so you can use non-capturing groups. (?:00|01) is a non-capturing group that will match either 00 or 01. You can also shorten it and write just 0[01], but that totally depends on your taste.

    And currently, your expression only matches lower-case strings. If you want it to work with upper-case, or even mixed-case strings, you can simply use the i modifier. It will make the pattern match the string case-insensitively.

    You can simplify your function to just:

    function preset($value) {
        return (bool) preg_match('/^[a-z]{2}(?:00|01)[0-9]{2,10}[0-9]{10}\.(?:jpe?g|png|gif)$/i',$value);
    }
    

    Demo

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

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?