【发布时间】:2013-06-15 07:36:21
【问题描述】:
http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip
urlencode($myurl);
问题在于urlencode 也会对斜杠进行编码,从而使 URL 无法使用。我怎样才能只编码最后一个文件名?
【问题讨论】:
标签: php url encoding urlencode encode
http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip
urlencode($myurl);
问题在于urlencode 也会对斜杠进行编码,从而使 URL 无法使用。我怎样才能只编码最后一个文件名?
【问题讨论】:
标签: php url encoding urlencode encode
类似于@Jeff Puckett 的回答,但作为一个函数,以数组作为替换:
function urlencode_url($url) {
return str_replace(['%3A','%2F'], [':', '/'], rawurlencode($url));
}
【讨论】:
首先,here's why 你应该使用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));
结果如下:
【讨论】:
试试这个:
$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 其余的。
【讨论】:
去掉文件名并转义它。
$temp = explode('/', $myurl);
$filename = array_pop($temp);
$newFileName = urlencode($filename);
$myNewUrl = implode('/', array_push($newFileName));
【讨论】: