duanlinjian5819 2012-02-09 18:23
浏览 57
已采纳

在变量中转换特殊字符以用于URL使用

So, this is the problem, i think everything is ok with this function, but URLs like:

reparações

are showing always as "reparaa-a-es".

The expected result should be "reparacoes"

EDIT:

So, the solution was simple, it seems php has a native function that does what i need:

rawurlencode ( string $str )


function generateSafeUrls($url = '') {
    ## normalize accented characters
    $url = strtr($url, "\xA1\xAA\xBA\xBF\xC0\xC1\xC2\xC3\xC5\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD\xE0\xE1\xE2\xE3\xE5\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8\xF9\xFA\xFB\xFD\xFF", "_ao_AAAAACEEEEIIIIDNOOOOOUUUYaaaaaceeeeiiiidnooooouuuyy"); 
    ## make sure its only english and dashes
    $url3 = preg_replace("/[^A-Za-z0-9_-]+/", "_", $url);
    ## return safe url
    return($url3);
}

What should be the problem?

Thanks guys.

  • 写回答

4条回答 默认 最新

  • dptsivmg82908 2012-02-09 18:51
    关注

    Try this on (using UTF8 decoding rather than trying to declare all the hexadecimals):

    function generateSafeUrls($url = ''){
       $bad = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ';
       $good = 'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr';  
       $url= strtr(utf8_decode($url), utf8_decode($bad), $good);
       return preg_replace("/[^A-Za-z0-9_-]+/", "_", $url);
    }
    

    However, as Conrad Shultz notes in comments, you don't necessarily need to do this... simple urlencode()ing should be fine... if you want cleaner looking urls, you should run the preg_replace so that the URLs don't have %20 etc, and you should probably strtolower()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部