我想从数据库中重命名文件。所以..我在下面写道。
它工作正常,除了具有长整数的名称。
(例如: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);
}
上面的表达式只匹配数字,但将匹配存储为字符串值,因此它不会丢失数字精度。
关于PHP重命名文件,以特殊名称开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24644226/