i need to remove % sign from file or image name in directory which string i use
$oldfile = "../wallpapers/temp-uploaded/".$file ;
$newfile = "../wallpapers/temp-uploaded/". trim( str_replace('%', '', $file));
rename("$oldfile","$newfile");
But its not work reply me which string i use ( trim, str_replace not work preg_replace how can i use for remove &%$ etc reply back
It could be an issue with other things as your logic seems correct. Firstly
rename("$oldfile","$newfile");
should be:
rename($oldfile,$newfile);
and:
$oldfile = "../wallpapers/temp-uploaded/".$file ;
should be:
$oldfile = '../wallpapers/temp-uploaded/'.$file ;
as there is no need for the extra interpolation. Will speed things up. Source: The PHP Benchmark (See "double (") vs. single (') quotes"). And here.
In regards to the problem, you have to do some proper debugging:
echo "[$oldfile][$newfile]";
look as expectedvar_dump(file_exists($oldfile),file_exists($newfile))
output true, false
file_get_contents($oldfile);
work?file_put_contents($newfile, file_get_contents($oldfile));
chmod 777
will do.if ( file_exists($newfile) ) { unlink($newfile); }
as you will have to delete the newfile if it exists, as you will be moving to it. Alternatively, you could append something to the filename if you do not want to do a replace. You get the idea.In regards to the replace question.
As you have said you would like %xx values removed, it is probably best to decode them first:
$file = trim(urldecode($file));
You could use a regular expression then:
$newfile = '../wallpapers/temp-uploaded/'.preg_replace('/[\\&\\%\\$\\s]+/', '-', $file); // replace &%$ with a -
or if you want to be more strict:
$newfile = '../wallpapers/temp-uploaded/'.preg_replace('/[^a-zA-Z0-9_\\-\\.]+/', '-', $file); // find everything which is not your standard filename character and replace it with a -
The \\
are there to escape the regex character. Perhaps they are not needed for all the characters I've escaped, but history has proven you're better safe than sorry! ;-)
$file = trim($file);
$oldfile = "../wallpapers/temp-uploaded/".$file ;
$newfile = "../wallpapers/temp-uploaded/".str_replace('%', '', $file);
rename($oldfile,$newfile);
To replace &%$
in the filename (or any string), I would use preg_replace.
$file = 'file%&&$$$name';
echo preg_replace('/[&%$]+/', '-', $file);
This will output file-name
. Note that with this solution, many consecutive blacklisted characters will result in just one -
. This is a feature ;-)