我在一个目录中有很多图像文件,它们的ID在一些关于它所包含内容的描述之间。
下面是该目录下文件的示例:de-te-mo-01-19-1084 moldura.JPG, ce-ld-ns-02-40-0453 senal.JPG, dp-bs- gu1-01-43 -1597-guante. jpg, am-ca-tw-04-30-2436 tweeter .jpg, am-ma-ac-02-26-0745 aceite.JPG, ca-cc-01-43-1427-F.jpg
我想要的是获得图像的ID *(nn-nn-nnnn)并使用该子字符串重命名文件。
*n作为一个数字。
上述列表的结果如下:01-19-1084.JPG, 02-40-0453.JPG, 01-43-1597.JPG, 04-30-2436.JPG, 02-26-0745.JPG, 01-43-1427.jpg.
这是我用来循环目录的代码:
$dir = "images";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($sub_str = preg_match($patern, $file))
{
rename($dir.'/'.$file, $sub_str.'JPG');
}
}
closedir($dh);
}
}
那么,我的$patern如何得到我想要的呢? $pattern必须像这样:
$pattern = "/^.*('d{2}-'d{2}-'d{4}).*'.jpg$/i"
该模式可以检查文件名并获得id作为匹配组。同样,preg_math返回数字,而不是字符串。匹配返回作为函数的第三个参数。而body必须像这样:
if(preg_match($patern, $file, $matches))
{
rename($dir.'/'.$file, $matches[1].'.JPG');
}
是不是就像:
^.*([0-9]{2})-([0-9]{2})-([0-9]{4}).*'.jpg$
解释:
^ Start of string
.* Match any characters by any number 0+
([0-9]{2}) 2 Digits
- Just a - char
([0-9]{2}) 2 Digits
- Just a - char
([0-9]{4}) 4 Digits
- Just a - char
.* Any character
'.jpg Extension and escape wildcard
$ End of string
现在在()
中有3个基团。你必须使用索引1、2和3