在php中编码url

时间:2014-07-16 13:35:10

标签: php url

我有字符串url变量;

$url ="http://carkva-gazeta.org/римско-католическая-церковь/";

我需要将$ url转换为:

"http://carkva-gazeta.org/%d1%80%d0%b8%d0%bc%d1%81%d0%ba%d0%be-%d0%ba%d0%b0%d1%82%d0%be%d0%bb%d0%b8%d1%87%d0%b5%d1%81%d0%ba%d0%b0%d1%8f-%d1%86%d0%b5%d1%80%d0%ba%d0%be%d0%b2%d1%8c/"

我试过了:rawurlencode($url);urlencode($url); 但结果是:

http%3A%2F%2Fcarkva-gazeta.org%2F%D1%80%D0%B8%D0%BC%D1%81%D0%BA%D0%BE-%D0%BA%D0%B0%D1%82%D0%BE%D0%BB%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B0%D1%8F-%D1%86%D0%B5%D1%80%D0%BA%D0%BE%D0%B2%D1%8C%2F

3 个答案:

答案 0 :(得分:2)

$url = "http://carkva-gazeta.org/";
$url .= urlencode("римско-католическая-церковь");

echo $url;

喜欢这样吗?

答案 1 :(得分:0)

可能这是最好的解决方案:

$url ="http://carkva-gazeta.org/римско-католическая-церковь/";

$x = parse_url($url);

echo $x['scheme'].'://'.$x['host'].strtolower(str_replace('%2F','/',urlencode($x['path'])));

我还使用strtolower将其设为小写,如你所愿

答案 2 :(得分:0)

假设您自动/动态地获取了URL字符串并且它不是一个固定的字符串,您可以在编写代码时简单地拆分它,您将需要这样的东西

$url = "http://carkva-gazeta.org/римско-католическая-церковь/";

// in case it is https, we don't want to hardcode http
$scheme = parse_url($url, PHP_URL_SCHEME);
$host = parse_url($url, PHP_URL_HOST);
// do not encode the first '/' or the last '/'
$encodedPath = strtolower(urlencode(substr(parse_url($url, PHP_URL_PATH), 1, -1)));

$encodedUrl = $scheme . "://" . $host . "/" . $encodedPath . "/";

DEMO