如何删除php字符串中的%sign
我需要从目录中的文件或图像名称中删除%sign 我用哪根弦如何删除php字符串中的%sign,php,string,sign,Php,String,Sign,我需要从目录中的文件或图像名称中删除%sign 我用哪根弦 $oldfile = "../wallpapers/temp-uploaded/".$file ; $newfile = "../wallpapers/temp-uploaded/". trim( str_replace('%', '', $file)); rename("$oldfile","$newfile"); 但它不起作用 回答我使用的字符串(修剪、str_替换无效 preg_replace如何用于删除和%$etc 回复由于
$oldfile = "../wallpapers/temp-uploaded/".$file ;
$newfile = "../wallpapers/temp-uploaded/". trim( str_replace('%', '', $file));
rename("$oldfile","$newfile");
但它不起作用
回答我使用的字符串(修剪、str_替换无效
preg_replace如何用于删除和%$etc
回复由于您的逻辑似乎正确,这可能是其他方面的问题。首先
rename("$oldfile","$newfile");
应该是:
rename($oldfile,$newfile);
$oldfile = '../wallpapers/temp-uploaded/'.$file ;
以及:
应该是:
rename($oldfile,$newfile);
$oldfile = '../wallpapers/temp-uploaded/'.$file ;
因为不需要额外的插值。将加快速度。来源:(请参阅“双(“)对单(“)引号”)。和
关于这个问题,您必须进行一些适当的调试:
是否与预期一致是否回显“[$oldfile][$newfile]”;
- 确保文件夹和旧文件存在
outputvar\u转储(文件存在($oldfile),文件存在($newfile))
true,false
有效吗file\u获取内容($oldfile);
file\u放入内容($newfile,file\u获取内容($oldfile));
- 确保您对该文件夹具有写入权限。通常
即可chmod 777
- 在重命名之前,执行:
,因为如果新文件存在,您将不得不删除它,因为您将移动到它。或者,如果您不想进行替换,您可以在文件名中附加一些内容。您明白了如果(file_exists($newfile)){unlink($newfile);}
$file = trim(urldecode($file));
然后可以使用正则表达式:
$newfile = '../wallpapers/temp-uploaded/'.preg_replace('/[\\&\\%\\$\\s]+/', '-', $file); // replace &%$ with a -
或者如果你想更严格一些:
$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 -
\\
是用来转义regex字符的。也许我转义的所有字符都不需要它们,但历史证明你比抱歉更安全!;-)要替换文件名(或任何字符串)中的&%$
,我会使用preg\u replace
$file = 'file%&&$$$name';
echo preg_replace('/[&%$]+/', '-', $file);
这将输出
文件名
。请注意,使用此解决方案,许多连续的黑名单字符将只产生一个-
。这是一个功能;-)如果图像名中有%$#等,则我需要它,然后将其替换为-或u。如何做到这一点?@balupton:为什么要将双引号转换为单引号?双引号与cor一样rect imo.@user395167-我已经更新了帖子以包含正则表达式,这是最好的方法。您可以选择您想要的内容,以及更严格的变体。@Znarkus。我已经更新了帖子以包含原因和参考源。但它不是从文件或图像文件名中删除%图像文件名是5035%2C.jpg如何要删除Percatage标志?我想你可以自己找出它@user395167;-)你有足够的材料来找出它。如果我现在就给你所有的答案,你不会是一个很好的教育者吧?:-)