如何在PHP字符串中去除百分号符号

3

我需要从目录中的文件或图像名称中删除百分号%,请问应该使用哪个字符串?

$oldfile = "../wallpapers/temp-uploaded/".$file ;
$newfile = "../wallpapers/temp-uploaded/". trim( str_replace('%', '', $file));

rename("$oldfile","$newfile");

但是它不起作用,回复我我应该使用哪个字符串(trim、str_replace都不起作用),preg_replace如何用于去除&%$等字符,回复。

3个回答

4
可能是由于其他原因导致的问题,因为您的逻辑似乎是正确的。首先
rename("$oldfile","$newfile");

should be:

rename($oldfile,$newfile);

并且:

$oldfile = "../wallpapers/temp-uploaded/".$file ;

should be:

$oldfile = '../wallpapers/temp-uploaded/'.$file ;

由于没有必要进行额外的插值,因此使用单引号将加快速度。来源:PHP基准测试(参见“双引号(“)与单引号(')”)。和这里

关于问题,您需要进行一些适当的调试:

  • 是否如预期那样显示echo "[$oldfile][$newfile]";
  • 确保文件夹和旧文件存在。
  • var_dump(file_exists($oldfile),file_exists($newfile))是否输出true, false
  • file_get_contents($oldfile);是否有效?
  • file_put_contents($newfile, file_get_contents($oldfile));是否有效?
  • 确保您拥有文件夹的写入权限。通常chmod 777就可以了。
  • 在重命名之前执行:if ( file_exists($newfile) ) { unlink($newfile); },如果新文件存在,则必须删除它,因为您将要移动到它。或者,如果您不想进行替换,可以在文件名后添加一些内容。你懂的。

关于替换问题。

由于您希望删除%xx值,因此最好先对其进行解码:

$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 -

这里的 \\ 是为了转义正则表达式中的特殊字符。可能并不是所有我转义的字符都需要它们,但历史证明,谨慎起见总是更好的选择!;-)


1
@balupton:为什么应该将双引号转换为单引号?在我看来,双引号同样正确。 - Markus Hedlund
@user395167 - 我已更新帖子,包括正则表达式,这是最好的方法。您可以选择您想要的内容和更严格的变体。@Znarkus。我已更新帖子,包括原因和参考来源。 - balupton
但它不能从文件或图像文件名中删除%符号 图像文件名为5035%2C.jpg 如何去掉百分号? - Hassan
需要将文件或图像文件中的空格" "删除。 - Hassan
1
我认为你可以自己想出那个问题的答案,@user395167 ;-)你已经有足够的材料来解决它了。如果我现在就把所有答案都给你,那我也不会成为一个好的教育者,对吧? :-) - balupton
显示剩余7条评论

2
$file = trim($file);
$oldfile = "../wallpapers/temp-uploaded/".$file ;
$newfile = "../wallpapers/temp-uploaded/".str_replace('%', '', $file);

rename($oldfile,$newfile);

0

要替换文件名(或任何字符串)中的&%$,我会使用preg_replace。

$file = 'file%&&$$$name';
echo preg_replace('/[&%$]+/', '-', $file);

这将输出文件名。请注意,使用此解决方案,许多连续的被列入黑名单的字符将导致只有一个-。这是一种特性;-)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接