URL百分号编码只能在PHP就像斯威夫特
我想编码在PHP中的URL在斯威夫特此相同的行为查询的是斯威夫特例如:URL百分号编码只能在PHP就像斯威夫特
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编码用于确定正确的百分比编码的 字符。忽略位于7位 ASCII范围之外的allowedCharacters中的任何字符。
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 extension
假设你没有/
需要进行编码,那么你就可以做到以下几点。
<?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
完整的示例,您需要解析域后的路径,使用'urlencode'对每个属于查询一部分的组件进行编码并重新构建url。 – jeroen
最好在组装URL时确实应对这些组件进行单独编码,而不是事后。如果不是你的价值是/?那么它是否应该被编码是完全不明确的。 – deceze