将UTF-8& white-space URL更改为Web应用程序的可读URL

时间:2015-01-01 21:34:51

标签: php url utf-8

如何转换(在php中)

  

http://images.example.com//images/2014/12/14-12-27 - 114545کریمباقریدر   تمرینتراکتور3(300x200).jpg

  

http://images.example.com//images/2014/12/14-12-27-114545%DA%A9%D8%B1%DB%8C%D9%85%20%D8%A8%D8%A7%D9%82%D8%B1%DB%8C%20%D8%AF%D8%B1%20%D8%AA%D9%85%D8%B1%DB%8C%D9%86%20%D8%AA%D8%B1%D8%A7%DA%A9%D8%AA%D9%88%D8%B13%20(300x200).jpg

注意:第一个网址中有空格。

我尝试了这段代码但是我失败了:

function url_path_encode($url) {
    $path = parse_url($url, PHP_URL_PATH);
    if (strpos($path,'%') !== false) return $url; //avoid double encoding
    else {
        $encoded_path = array_map('urlencode', explode('/', $path));
        return str_replace($path, implode('/', $encoded_path), $url);
    }
  

http://images.example.com//images/2014/12/14-12-27-114545%DA%A9%D8%B1%DB%8C%D9%85+%D8%A8%D8%A7%D9%82%D8%B1%DB%8C+%D8%AF%D8%B1+%D8%AA%D9%85%D8%B1%DB%8C%D9%86+%D8%AA%D8%B1%D8%A7%DA%A9%D8%AA%D9%88%D8%B13+%28300x200%29.jpg

在线工具示例:http://meyerweb.com/eric/tools/dencoder/

3 个答案:

答案 0 :(得分:0)

你试试这个吗?

(PHP 4,PHP 5) urlencode - URL编码字符串

<?php
echo '<a href="mycgi?foo=', urlencode($userinput), '">';
?>

答案 1 :(得分:0)

您正在寻找rawurlencode

function url_path_encode($url)
{
    $ret = '';
    if(false === $parts = parse_url($url)) {
        return false;
    }

    if (isset($parts['scheme'])) {
        $parts['scheme'] = $parts['scheme'] . '://';
    }

    if (isset($parts['path'])) {
        $parts['path'] = join('/', array_map('rawurlencode', explode('/', $parts['path'])));;
    }

    // ...

    return implode('', $parts);
}

echo url_path_encode('http://images.example.com//images/2014/12/14-12-27-114545کریم باقری در تمرین تراکتور3 (300x200).jpg');

答案 2 :(得分:0)

最后我通过这个函数解决了它:

function url_path_encode($url) {
    $unescaped = array(
        '%2D'=>'-','%5F'=>'_','%2E'=>'.','%21'=>'!', '%7E'=>'~',
        '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')'
    );
    $reserved = array(
        '%3B'=>';','%2C'=>',','%2F'=>'/','%3F'=>'?','%3A'=>':',
        '%40'=>'@','%26'=>'&','%3D'=>'=','%2B'=>'+','%24'=>'$'
    );
    $score = array(
        '%23'=>'#'
    );
    return strtr(rawurlencode($url), array_merge($reserved,$unescaped,$score)); 
}