PHP rename files starting with a special name?

I wanted to rename files from the database. so .. I wrote below. works fine except for names with long int lengths. (for example: bartmp_9404865346.jpgdoes not work, but bartmp_585558.jpgworks)

$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);
}

Can you give me some alternative way to do this or a little hint to change this. thank.

+4
source share
2 answers

You use %dfor a decimal point that seems superficially correct:

$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]);
+1

%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);
}

, , .

+4

Source: https://habr.com/ru/post/1547679/


All Articles