Encode the url including hyphen(-) and dot(.) in php

梦想的初衷 提交于 2019-11-27 17:49:21

问题


I need the encoded URL for processing in one of the API, but it requires the full encoded URL. For example, the URL from:

http://test.site-raj.co/999999?lpp=1&px2=IjN

has to become an encoded URL, like:

http%3a%2f%test%site%2draj%2eco%2f999999%3flpp%3d1%26px2%3dIjN

I need every symbol to be encoded, even the dot(.) and hyphen(-) like above.


回答1:


Try this. Inside a function maybe if you are using it more than once...

$str = 'http://test.site.co/999999?lpp=1&p---x2=IjN';
$str = urlencode($str);
$str = str_replace('.', '%2E', $str);
$str = str_replace('-', '%2D', $str);
echo $str;



回答2:


This will encode all characters that are not plain letters or numbers. You can still decode this with the standard urldecode or rawurldecode:

function urlencodeall($x) {
    $out = '';
    for ($i = 0; isset($x[$i]); $i++) {
        $c = $x[$i];
        if (!ctype_alnum($c)) $c = '%' . sprintf('%02X', ord($c));
        $out .= $c;
    }
    return $out;
}



回答3:


Why don't you use rawurlencode

for example rawurlencode("http://test.site-raj.co/999999?lpp=1&px2=IjN")



来源:https://stackoverflow.com/questions/12093050/encode-the-url-including-hyphen-and-dot-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!