【问题标题】:PHP urlencode - encode only the filename and dont touch the slashesPHP urlencode - 只对文件名进行编码,不要碰斜线
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      首先,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));
      

      结果如下:

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

      【讨论】:

        【解决方案3】:

        试试这个:

        $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 中不能存在正斜杠,即使它不应该存在?从技术上讲,它应该被转义,但如果不是的话怎么办。 IE。 “example.com/thing?redirect=www.example.com/other-thing”。也许这并不重要,因为 URL 无效,但是是否有解决方案来正确编码整个字符串?
        【解决方案4】:

        去掉文件名并转义它。

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

        【讨论】:

        • 这是一个缓慢的解决方案。无需将字符串转储到数组中。
        猜你喜欢
        • 2013-01-21
        • 1970-01-01
        • 1970-01-01
        • 2014-10-03
        • 2015-01-14
        • 2012-06-14
        • 1970-01-01
        • 1970-01-01
        • 2011-06-25
        相关资源
        最近更新 更多