2012-01-30 185 views
0

如何編碼包含Unicode的URL?我想將它傳遞給命令行工具,我需要先對它進行編碼。使用html格式的URL編碼

<form action="index.php" method="get" > 
<input type="text" name="find" value="عربي" /><br /> 
<input type="submit" value="search" /> 
<form /> 

示例: http://localhost/index.php?find =عربي

http://localhost/index.php?find=%DA%D1%C8%ED變得

+0

http://www.drupalcode.com/api/function/mb_urlencode/contrib-5.x-1.x – 2012-01-30 14:45:08

+0

所以你想'عربي'作爲參數值,但不知道如何將其轉換爲'%DA%D1%C8%ED',對嗎? – Gumbo 2012-01-30 14:45:46

+0

爲什麼你不使用POST? POST請求將正確編碼。 – 2012-01-30 14:46:11

回答

2
$ cat testme 
#!/usr/local/bin/php 
<?php 

$chars = array("d8", "b9", "d8", "b1", "d8", "a8", "d9", "8a"); 

foreach ($chars as $one) { 
    $string .= sprintf("%c", hexdec($one)); 
} 

print "String: " . $string . "\n"; 
print "Encoded: " . urlencode($string) . "\n"; 

?> 
$ ./testme 
String: عربي 
Encoded: %D8%B9%D8%B1%D8%A8%D9%8A 
$ 
1

%DA%D1%C8%ED不是Unicode序列,但在URL其他編碼編碼的序列。 عربي以Unicode URL編碼後應成爲%D8%B9%D8%B1%D8%A8%D9%8A

如果要構建有效的URL與您可以使用類似的Unicode字符:

$url = 'http://localhost/index.php?find=عربي'; 

$url_parts = parse_url($url); 
$query_parts = array(); 
parse_str($url_parts['query'], $query_parts); 
$query = http_build_query(array_map('rawurlencode', $query_parts)); 

$url_parts['query'] = $query; 
$encoded_url = http_build_url($url_parts); 

注:這隻會編碼URL的query一部分。