URL百分比只对PHP中的查询进行编码,就像Swift中一样



我想以Swift中相同的行为在PHP中编码URL,这里是Swift的例子:

let string = "http://site.se/wp-content/uploads/2015/01/Hidløgsma.jpg"
let encodedString = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

结果:http://site.se/wp-content/uploads/2015/01/Hidl%25F8gsma.jpg

如何在PHP中获得相同的结果,即只对查询进行编码并使用示例字符串返回相同结果的函数。以下是有关Swift函数的文档:

func addingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String?

不能对整个URL字符串进行百分比编码,因为每个URL组件指定了一组不同的允许字符。对于例如,URL的查询组件允许使用"@"字符,但是该字符必须在密码组件中进行百分比编码。

UTF-8编码用于确定正确的编码百分比字符。allowedCharacters中7位之外的任何字符ASCII范围被忽略。

https://developer.apple.com/documentation/foundation/nsstring/1411946-addingpercentencoding

urlQueryAllowed

URL的查询组件是紧跟在问号。例如,在URL中http://www.example.com/index.php?key1=value1#jumpLink,查询组件为key1=value1。

https://developer.apple.com/documentation/foundation/nscharacterset/1416698-urlqueryallowed

这很棘手:

首先,我建议使用PECL HTTP扩展

假设您没有需要编码的/,那么您可以执行以下操作。

<?php
$parsed = parse_url("http://site.se/wp-content/uploads/2015/01/Hidløgsma.jpg"); //Get the URL bits
if (isset($parsed["path"])) {
$parsed["path"] = implode("/", array_map('urlencode', explode("/",$parsed["path"]))); //Break the path according to slashes and encode each path bit
}
//If you need to do the query string then you can also do:
if (isset($parsed["query"])) {
parse_str($parsed["query"],$result); //Parse and encode the string
$parsed["query"] = http_build_query(
array_combine(
array_map('urlencode', array_keys($result)),
array_map('urlencode', array_values($result))
)
);
}
//Maybe more parts need encoding?
//http_build_url needs the PECL HTTP extension
$rebuilt = http_build_url($parsed); //Probably better to use this instead of writing your own

然而,如果你不想为此安装扩展,那么替换http_build_url的简单方法是:

$rebuilt = $parsed["scheme"]
."://"
.(isset($parsed["user"])?$parsed["user"]:"")
.(isset($parsed["pass"])?":".$parsed["pass"]:"")
.$parsed["host"]
.(isset($parsed["port"])?":".$parsed["port"]:"")
.(isset($parsed["path"])?$parsed["path"]:"")
.(isset($parsed["query"])?"?".$parsed["query"]:"")
.(isset($parsed["fragment"])?"#".$parsed["fragment"]:"");
print_r($rebuilt);

上的完整演示http://sandbox.onlinephpfunctions.com/code/65a3da9a92c6f55a45138c73beee7cba43bb09c3

相关内容

最新更新