PHP urlencode - 只对文件名进行编码,不要碰斜杠


PHP urlencode - encode only the filename and dont touch the slashes

http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip
urlencode($myurl);

问题是urlencode也会对斜杠进行编码,这使得 URL 无法使用。如何只编码最后一个文件名?

试试这个:

$str = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip';
$pos = strrpos($str, '/') + 1;
$result = substr($str, 0, $pos) . urlencode(substr($str, $pos));

您正在寻找最后一次出现的斜杠符号。它前面的部分是可以的,所以只需复制它。其余的urlencode

首先,这就是为什么你应该使用 rawurlencode 而不是 urlencode .

要回答您的问题,与其大海捞针并冒着不在您的 URL 中编码其他可能的特殊字符的风险,只需对整个内容进行编码,然后修复斜杠(和冒号(。

<?php
$myurl = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip';
$myurl = rawurlencode($myurl);
$myurl = str_replace('%3A',':',str_replace('%2F','/',$myurl));

结果是:

http://www.example.com/some_folder/some%20file%20%5Bthat%5D%20needs%20%22to%22%20be%20%28encoded%29.zip

拉下文件名并转义它。

$temp = explode('/', $myurl);
$filename = array_pop($temp);
$newFileName = urlencode($filename);
$myNewUrl = implode('/', array_push($newFileName));

类似于@Jeff Puckett的答案,但作为一个以数组作为替换的函数:

function urlencode_url($url) {
    return str_replace(['%3A','%2F'], [':', '/'], rawurlencode($url));
}