简体   繁体   中英

What is wrong with this regex PHP code?

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?

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

No need for the overhead of regex here at all. Perhaps simple glob() and str_replace() would meet your needs.

$photoPath="../pic/";

$replacements = array(
    '_5' => '_five',
    '_10' => '_ten'
);

foreach ($replacements as $pattern => $replace) {
    $files = glob($photoPath . '*' . $pattern . '*');
    foreach($files as $file) {
       $old_name = $file;
       $new_name = str_replace($pattern, $replace, $old_name); 
       rename($old_name, $new_name);
    }
}

Here we don't even use regex or PHP string searching functionality to find the files we want to change. We use glob() which is basically a direct call to underlying libc glob() function and should perform significantly better and with less memory usage than the DirectoryIterator with post-filter functionality you are currently using. DirectoryIterator is probably overkill here anyway unless you are doing more complex file operations. glob() would filter your file names for you, meaning you are not doing useless regex searches against every file contained in DirectoryIterator object like you are currently doing.

The actual filepath name change is executed using basic str_replace(). You don't currently show how you are doing this, but I would imagine you would implement something similar or possibly just use preg_replace() rather than preg_match() if you desire to stick with regex approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM