gpt4 book ai didi

php - 如何像浏览器在 PHP 中那样将 utf8 编码为 url?

转载 作者:行者123 更新时间:2023-12-01 09:01:58 24 4
gpt4 key购买 nike

在浏览器中输入此 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

上面的 url 只是一个简单的例子,我需要一个也适用的通用解决方案
http://www.example.com/ä
http://www.example.com/ä?foo=ä&bar=ö
http://www.example.com/Περιβάλλον?abc=Περιβάλλον

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

最佳答案

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

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

关于php - 如何像浏览器在 PHP 中那样将 utf8 编码为 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15427321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com