在 php 中对包含连字符 (-) 和点 (.) 的 url 进行编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12093050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:48:07  来源:igfitidea点击:

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

phpurlencodeencode

提问by Rajasekar PHP

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

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

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

has to become an encoded URL, like:

必须成为编码的 URL,例如:

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.

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

回答by Dênis Montone

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;

回答by Boann

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

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

回答by benegan1991

Why don't you use rawurlencode

你为什么不使用 rawurlencode

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

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