Balconsky
Balconsky

Reputation: 2244

Encode url in php

I have string url variable;

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

I need transform $url to:

"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/"

I have tried: rawurlencode($url); and urlencode($url); But result is:

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

Upvotes: 0

Views: 119

Answers (3)

Patrick Q
Patrick Q

Reputation: 6393

Assuming that you are getting your URL string automatically/dynamically and that it is not a fixed string that you can simply split while writing your code, you'll want something like this

$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

Upvotes: 0

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

Probably that's the best solution:

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

$x = parse_url($url);

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

I've used also strtolower to make it lowercase as you wanted

Upvotes: 0

Ian
Ian

Reputation: 3676

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

echo $url;

Like so?

Upvotes: 2

Related Questions