dongshanyan0322 2015-11-11 17:30
浏览 21
已采纳

这个正则表达式PHP代码有什么问题?

I have a folder that stores some thousands of pictures files. I want to change the name of each file that matches the condition. The idea is if the file name has _10 change to _ten, if has _5 change to _five. So, xxdf23_10hy.jpg should be xxdf23_tenhy.jpg, 16_5_gt5.jpg should change to 16_five_gt5.jpg. But if file mane is gdjd_7.jpg, do nothing.

The code is working good, but it is matching the string ".." that should not be matched.

This is the part of the code:

$photoPath="../pic/";
$dir = new DirectoryIterator($photoPath);
foreach ($dir as $fileinfo) {
    $filename = $fileinfo->getFilename();
    if(preg_match($filename, "/_10/")){
      //change te name to "_ten"
    }
    elseif(preg_match($filename, "/_5/")){
      //change te name to "_five"
    }
}

Something is not good with the way I am using the preg_match function. But if I try it inside regex tester it works good.

What am I missing?

  • 写回答

2条回答 默认 最新

  • drp935159 2015-11-11 17:34
    关注

    You've got your subject and pattern switched in the preg_match() commands. Try this:

    if (preg_match("/_10/", $filename)) {
        // more code
    }
    

    http://php.net/manual/en/function.preg-match.php

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

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作