drxnfdx798517235 2014-09-28 02:32
浏览 33
已采纳

PHP:fopen(UrlWithWhiteSpaces)

As you can see on the title, I am trying to fopen() a Url with whitespaces. Other stackoverflow posts didn't help really, could it possibly be that they are outdated?
I have tried:

  • urlencode
  • rawurlencode

None of the above works , http://test.com/two - words.jpg this gives me:

  • urlencode: http%3A%2F%2Ftest.com%2Ftwo+-+words.jpg
  • rawurlencode: http%3A%2F%2Ftest.com%2Ftwo%20-%20words.jpg

When i am trying to clearly get http://test.com/two%20-%20words.jpg , which is what the browser shows when you type http://test.com/two - words.jpg and hit enter.

Which function do I have to use to make those conversions from space to %20 , and all the other possible conversions i could need(which i can't think of any more, but i am pretty sure they exist, maybe on special symbols) ?

  • 写回答

1条回答 默认 最新

  • doulu4534 2014-09-28 02:37
    关注

    Use preg_replace:

    $newUrl = preg_replace('/ /', '%20', 'http://test.com/two - words.jpg');
    
    echo $newUrl;
    

    OUTPUT

    http://test.com/two%20-%20words.jpg
    

    And alternatively str_replace:

    $newUrl = str_replace(' ', '%20', 'http://test.com/two - words.jpg');
    

    But more generally you will need to encode more than just the space. I made this function, if you don't want to use urlencode or rawurlencode, this is what you are looking for:

    function encodeURI($URI)
    {
        return str_replace(array('%', '^', '+', '{', '[', '}', ']', '"', '|', '\\', '<', '>', ' '),
            array('%25', '%5E', '%2B', '%7B', '%5B', '%7D', '%5D', '%22', '%7C', '%5C', '%3C', '%3E', '%20'), $URI);
    }
    

    example

    echo encodeURI('http://test.com/two - ["word<><s.jpg');
    

    OUTPUT

    http://test.com/two%20-%20%5B%22word%3C%3E%3Cs.jpg
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)