PHP重命名文件,以特殊的名称开始


PHP rename files, starting with special name?

我想从数据库中重命名文件。所以,我写了下面。它工作得很好,除了长int的名字。(例如:bartmp_9404865346.jpg不工作,但bartmp_585558.jpg工作)

$subject = '[img]http://www.example.org/users/uploads/bartmp_9404865346.jpg[/img]
            Hello world
            [img]http://www.example.org/users/uploads/bartmp_585558.jpg[/img]';
preg_match_all('/'[img'](.*?)'['/img']/', $subject, $files);

foreach ($files[1] as $file) {
  $n = sscanf($file, "http://www.example.org/users/uploads/bartmp_%d.jpg");
  $refile = sprintf("http://www.example.org/users/uploads/mybar_%d.jpg", $n[0]);
  rename($file, $refile);
}

你能给我任何改变的方法来做这件事或一点提示来修改它吗?谢谢。

%d格式说明符只接受适合整数的数字(取决于平台,可能是2^31或2^63);在不损失精度的情况下,在这种情况下,正则表达式可能会更好:

if (preg_match('#^http://www.example.org/users/uploads/bartmp_('d+)'.jpg$#', $file, $matches)) {
    $refile = sprintf('http://www.example.org/users/uploads/mybar_%s.jpg', $matches[1]);
    rename($file, $refile);
}

上面的表达式只匹配数字,但将匹配存储为字符串值,因此它不会失去数字精度。

您正在使用%d作为小数,这似乎表面上是正确的:

$n = sscanf($file, "http://www.example.org/users/uploads/bartmp_%d.jpg");
$refile = sprintf("http://www.example.org/users/uploads/mybar_%d.jpg", $n[0]);

问题是php和其他编译为32位的语言中的最大数值是2147483647,因此9404865346无法运行。相反,您应该像这样将值提取为字符串:

$n = sscanf($file, "http://www.example.org/users/uploads/bartmp_%s.jpg");
$refile = sprintf("http://www.example.org/users/uploads/mybar_%s", $n[0]);