dpruwm6206 2016-04-21 17:24
浏览 52
已采纳

PHP正则表达式忽略以双__underscore开头的文件

I have tried, but I simply can't wrap my head around regex in PHP. I need a regex that does the following:

  • ignores files that start with double __underscore. (for example __file.jpg)
  • ignores files that end with "thumb". (for example somethumb.jpg or thumb.jpg)
  • ignores all file types but gif|jpg|png|jpeg

I have the following for now, which seems to fulfill #2 and #3, but not #1:

preg_match(/(?<!thumb)\.(gif|jpg|png|jpeg)$/i, $file)

Any help much appreciated!

  • 写回答

2条回答 默认 最新

  • dongtangdao7232 2016-04-21 17:35
    关注

    If I understood third point correctly it means that it should end with all these file extensions. Considering this, the following will work

    1st Solution

    (?!^__|.*thumb\.(gif|jpg|png|jpeg))(^.*)(?=\.(gif|jpg|png|jpeg)$)
    

    Regex Demo

    Towards an efficient solution

    2nd Solution

    ^(?!__|.*thumb\.(?:gif|jpg|png|jpeg))(.*(?=\.(?:gif|jpg|png|jpeg)$).*$)
    

    3rd Solution (suggested by Wiktor in comments)

    ^(?!__|.*thumb\.(?:gif|jpg|png|jpeg))(?=.*\.(?:gif|jpg|png|jpeg)$).*
    

    4th Solution (suggested by Casimir in comments)

    ^(?!__)(?:[^.
    ]*\.)*+(?<!thumb\.)(?:jpe?g|png|gif)$
    

    PHP Code

    $re = "/^(?!__|.*thumb\\.(?:gif|jpg|png|jpeg))(?=.*\\.(?:gif|jpg|png|jpeg)$)(.*)/m";
    $str = "__abcd.jpg
    thumbabcd.gif
    thumbabcdthumb.jpg
    thumbs.jpg
    somethumb.jpg
    thumb.jpg
    abcd.jpg
    abcd.jps"; 
    
    preg_match_all($re, $str, $matches);
    

    Ideone Demo

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

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算