2012-01-30 159 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一部分。