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

URL Percent Encoding only the query in PHP like in Swift

我想在 PHP 中以与 Swift 相同的行为对 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 中获得相同的结果,即仅对查询进行编码的函数和 returns 与示例字符串相同的结果。这是关于 Swift 函数的文档:

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

Entire URL strings cannot be percent-encoded, because each URL component specifies a different set of allowed characters. For example, the query component of a URL allows the “@” character, but that character must be percent-encoded in the password component.

UTF-8 encoding is used to determine the correct percent-encoded characters. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.

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

urlQueryAllowed

The query component of a URL is the component immediately following a question mark (?). For example, in the URL http://www.example.com/index.php?key1=value1#jumpLink, the query component is 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