如何删除 php 字符串中的%符号
我需要从目录中的文件或图像名称中删除 % 符号 我使用哪个字符串
$oldfile = "../wallpapers/temp-uploaded/".$file ;
$newfile = "../wallpapers/temp-uploaded/". trim( str_replace('%', '', $file));
rename("$oldfile","$newfile");
但它不起作用 回复我使用哪个字符串(trim、str_replace不起作用 preg_replace 我如何用于删除 &%$ 等 回复
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能是其他事情的问题,因为你的逻辑似乎是正确的。 首先
应该是:
并且:
应该是:
因为不需要额外的插值。会加快速度。资料来源:PHP 基准(请参阅“双引号 (”) 与单引号 (')”)。以及此处
。关于这个问题,您必须进行一些适当的调试:
echo "[$oldfile][$newfile]";
看起来是否符合预期var_dump(file_exists($oldfile),file_exists($newfile))
输出true, false
file_get_contents($oldfile);
有效吗chmod 777
即可,if ( file_exists($newfile) ) { unlink($newfile); }
因为您必须删除新文件(如果它存在),因为您将移动到它,或者,您可以在文件名中附加一些内容。您不想进行替换。你明白了。关于替换问题。
正如您所说,您希望删除 %xx 值,最好先对它们进行解码:
您可以使用正则表达式,然后:
或者如果您想要更多strict:
\\
用于转义正则表达式字符。也许我逃脱的所有角色都不需要它们,但历史已经证明,安全总比后悔好! ;-)It could be an issue with other things as your logic seems correct. Firstly
should be:
and:
should be:
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))
outputtrue, 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:
You could use a regular expression then:
or if you want to be more strict:
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! ;-)要替换文件名(或任何字符串)中的
&%$
,我将使用 preg_replace。这将输出
文件名
。请注意,使用此解决方案时,许多连续的黑名单字符将仅生成一个-
。这是一个功能;-)To replace
&%$
in the filename (or any string), I would use preg_replace.This will output
file-name
. Note that with this solution, many consecutive blacklisted characters will result in just one-
. This is a feature ;-)