在php中对url进行编码,包括连字符(-)和句点(.)


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

我需要编码的URL在其中一个API中进行处理,但它需要完整的编码URL。例如,URL来自:

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

必须成为编码的URL,如:

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

我需要对每个符号进行编码,甚至像上面那样的点(.)和连字符(-)。

试试这个。在函数内部,如果你不止一次使用它。。。

$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;

这将对所有非普通字母或数字的字符进行编码。您仍然可以使用标准urldecode或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;
}

为什么不使用rawurlencode

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