2017-10-06 48 views
2

我想編碼在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

+0

完整的示例,您需要解析域後的路徑,使用'urlencode'對每個屬於查詢一部分的組件進行編碼並重新構建url。 – jeroen

+2

最好在組裝URL時確實應對這些組件進行單獨編碼,而不是事後。如果不是你的價值是/?那麼它是否應該被編碼是完全不明確的。 – deceze

回答

1

這是棘手:

首先所有的,我建議使用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