2016-02-18 118 views
0

我試圖編碼的網站目前的RFC 3986標準,使用此功能:URL編碼和str_replace函數

function getUrl() { 

     $url = @($_SERVER["HTTPS"] != 'on') ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"]; 
     $url .= ($_SERVER["SERVER_PORT"] !== 80) ? ":".$_SERVER["SERVER_PORT"] : ""; 
     $url .= $_SERVER["REQUEST_URI"]; 

     $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D'); 
     $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]"); 

     return str_replace($entities, $replacements, urlencode($url)); 

    } 

的URL添加:http://localhost/test/test-countdown/?city=hayden&eventdate=20160301 返回:http://localhost/test/test-countdown/?city=hayden&eventdate=20160301//&更換

不編碼

回答

0

如果您想要以這種格式編碼URL(非網站):

http%3A%2F%2Flocalhost%2Ftest%2Ftest-countdown%2F%3Fcity%3Dhayden%26eventdate%3D20160301 

使用內置的php函數rawurlencode($url)

1

雖然典型的解決方案是簡單地使用rawurlencode()作爲fusion3k說,值得注意的是,滾動自己的解決方案時,你應該:

  1. 更緊密地聽規格和編碼所有字符不是字母數字或-_.~之一。
  2. 更懶惰,拒絕輸入所有這些實體。我的經驗法則是,我沒有超過10個數組條目,沒有一個很好的理由。自動化!

代碼:

function encode($str) { 
    return preg_replace_callback(
     '/[^\w\-_.~]/', 
     function($a){ return sprintf("%%%02x", ord($a[0])); }, 
     $str 
    ); 
} 

var_dump(encode('http://localhost/test/test-countdown/?city=hayden&eventdate=20160301')); 

結果:

string(88) "http%3a%2f%2flocalhost%2ftest%2ftest-countdown%2f%3fcity%3dhayden%26eventdate%3d20160301" 
0

其他人所說的rawurlencode(),但你的代碼的問題是,你有你的陣列倒退。

切換您的數組是這樣的:

function getUrl() { 
 

 
    $url = @($_SERVER["HTTPS"] != 'on') ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"]; 
 
    $url .= ($_SERVER["SERVER_PORT"] !== 80) ? ":".$_SERVER["SERVER_PORT"] : ""; 
 
    $url .= $_SERVER["REQUEST_URI"]; 
 

 
    $entities = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");  
 
    $replacements = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D'); 
 

 
    return str_replace($entities, $replacements, urlencode($url)); 
 
}