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 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题