问题:URL Percent Encoding only the query in PHP like in 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 的查询组件是紧跟问号 (?) 的组件。例如,在 URLhttp://www.example.com/index.php?key1u003dvalue1#jumpLink中,查询组件为 key1u003dvalue1。

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

Logo

更多推荐