3

在浏览器中输入此 url 时:http://www.google.com/?q=ä

发送的 url 实际上是http://www.google.com/?q=%C3%A4

我想用 Php 做同样的转换——怎么做?

我尝试了什么:

$url = 'http://www.google.com/?q=ä'; //utf8 encoded

echo rawurlencode($url);
//gives http%3A%2F%2Fwww.google.com%2F%3Fq%3D%C3%A4

$u = parse_url($url);
echo $url['scheme'].'://'.$url['host'].$url['path'].'?'.rawurlencode($url['query']);
//gives http://www.google.com/?q%3D%C3%A4

上面的网址只是一个简单的例子,我需要一个通用的解决方案,也适用于

http://www.example.com/ä
http://www.example.com/ä?foo=ä&bar=ö
http://www.example.com/Περιβάλλον?abc=Περιβάλλον

这里提供的答案不够通用: How to encode URL using php like browsers do

4

2 回答 2

13

好的,花了我一些时间,但我认为我有通用的解决方案:

function safe_urlencode($txt){
  // Skip all URL reserved characters plus dot, dash, underscore and tilde..
  $result = preg_replace_callback("/[^-\._~:\/\?#\\[\\]@!\$&'\(\)\*\+,;=]+/",
    function ($match) {
      // ..and encode the rest!  
      return rawurlencode($match[0]);
    }, $txt);
  return ($result);
}

基本上,它使用URL 保留字符http://www.ietf.org/rfc/rfc3986.txt)+更多字符(因为我认为“点”也应该单独留下)分割字符串,并在rawurlencode ()其余的部分。

echo safe_urlencode("https://www.google.com/?q=ä");
// http://www.google.com/?q=%C3%A4

echo safe_urlencode("https://www.example.com/Περιβάλλον?abc=Περιβάλλον");
// http://www.example.com/%CE%A0%CE%B5%CF%81%CE%B9%CE%B2%CE%AC%CE%BB%CE%BB%CE%BF%CE%BD?abc=%CE%A0%CE%B5%CF%81%CE%B9%CE%B2%CE%AC%CE%BB%CE%BB%CE%BF%CE%BD
// ^ This is some funky stuff, but it should be right
于 2013-03-15T08:07:34.140 回答
-1

Looks that you want encode the query part of the URI without modify schema and host.

Preamble

There are no generic functions shipped by the language to achieve that because is not possible for the language to know if you will use the encoded string for a redirect or as query argument (?url=http%3A%3A....)

So the developer have to extract the part to encode as you did.

Answer

Encapsulate your own code as a function.

function encodeUrlQuery($url) {
  $u = parse_url($url);
  return $u['scheme'].'://'.$u['host'].$u['path'].'?'.rawurlencode($u['query']);
}

echo encodeUrl('http://www.google.com/?q=ä');
于 2013-03-15T08:09:35.610 回答