url解析

//规则
public $urlMap = array(
    array('module',     '',     '\w+',      NULL),
    array(
        array('type',     't',     '\d+',      0),
        array('page',     'p',     '\d+',      1)
    )

);

private function _parseUrl() {
   //$uri = "/xxxx/xxxxx/";
   $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : "";
   $uris = explode("/", trim($uri, "/"));
   for ($i=0, $n=0, $count=count($this->urlMap); $i<$count;){
      $urlMap = $this->urlMap[$i];
      if (is_array($urlMap[0])){

         $ok     = false;
         $match  = $this->_isMatch($urlMap, $uris[$n]);

         foreach ($urlMap as $map){
            $key = $map[0];
            $this->defaultValue[$key]   = $map[3];
            if ($match && isset($uris[$n]) && preg_match("/".$map[1]."(".$map[2].")/", $uris[$n], $mat)){
               $val = ($mat[1] === NULL || $mat[1] === 'undefined') ? $map[3] : $mat[1];
               $this->urlResult[$key] = array(
                     $map[1],
                     $val,
                     $map[3]
               );
               $this->requestParams[$key] = $val;
               $ok = true;
            }
            else {
               $this->urlResult[$key] = array($map[1], $map[3], $map[3]);

            }
         }
         if ($ok) $n++;
      }
      else {
         $key = $urlMap[0];
         $this->defaultValue[$key]   = $urlMap[3];
         $matchStr = "/^".$urlMap[1]."(".$urlMap[2].")$/";
         if(isset($urlMap[4])){
            $matchStr = "/^".$urlMap[1]."(".$urlMap[2].")".$urlMap[4]."$/";
         }
         if (preg_match($matchStr, $uris[$n], $mat)){

            $val = ($mat[1] === NULL || $mat[1] === 'undefined') ? $urlMap[3] : $mat[1];
            if ($key == 'keyword') {
               if (strpos($val, '+') === false) {
                  $val = rawurldecode($val);
               }
               else {
                  $val = urldecode($val);
               }
            }

            $this->urlResult[$key] = array(
                  $urlMap[1],
                  $val,
                  $urlMap[3]
            );
            if(isset($urlMap[4])){
               $this->urlResult[$key][] = $urlMap[4];
            }
            $this->requestParams[$key] = $val;
            $n++;
         }
         else {
            $this->urlResult[$key] = array($urlMap[1], $urlMap[3], $urlMap[3]);
         }
      }

      $i++;
   }


private function _isMatch($regexps, $str)
{
   $ret = array();
   foreach ($regexps as $val) {
      $ret[] = "({$val[1]}{$val[2]})?";
   }
   $regexp = "/^".implode("", $ret)."$/";
   return preg_match($regexp, $str);
}

url:

http://www.xxxx.com/abcde/t2/

解析后($this->requestParams):

Array ( [module] => abcde [type] => 2 [page] => 1 )


<think>好的,用户想了解如何实现URL解码,并需要示例代码。首先,我需要回忆URL解码的基本概念和作用。URL解码主要是将编码过的URL字符串转换回原始格式,比如把"%20"变回空格。接下来,我应该考虑不同编程语言的实现方法,因为用户提供的引用里提到了PHP、Java、C语言等,可能用户希望看到多种语言的示例。 首先,确定用户可能使用的语言。用户没有明确指定,所以最好覆盖常见的几种,比如PHP、Java、Python、JavaScript和C语言。这样能够满足不同开发者的需求。然后,根据引用中的资料,PHP使用urldecode函数,Java用URLDecoder类,Python有urllib.parse模块,JavaScript有decodeURIComponent函数,而C语言需要手动处理或者用库函数。 接下来,每个示例需要简洁明了,展示解码前后的对比。比如PHP中的代码示例,用户提供的引用里有编码的例子,解码应该类似。需要注意特殊字符的处理,比如空格变成%20,中文或其他多字节字符的编码问题。同时,要提到不同语言中可能存在的差异,比如JavaScript中的两种解码函数区别。 另外,用户可能关心为什么需要URL编解码,引用[4]提到是因为特殊字符和多字节编码的问题,需要在回答中简要说明。还要注意提醒用户注意不同语言对空格的编码差异,比如+和%20,确保解码时正确处理。 最后,检查示例代码的正确性,确保没有语法错误,并说明运行结果。例如Java示例中的URLDecoder.decode方法需要指定编码格式,如UTF-8,避免乱码。Python 3的示例要区分版本,因为urllib在Python 2和3中有变化,用户可能容易混淆,所以需要明确说明。 结步骤:解释URL解码的作用,列举各语言示例,注意事项,以及可能的问题点。确保回答结构清晰,覆盖主要语言,并引用提供的资料作为参考。</think>### URL解码实现方法与示例代码 URL解码是将经过百分比编码(如`%20`表示空格)的字符串还原为原始字符的过程,常用于处理表单提交、API参数传递等场景[^4]。 #### 一、各语言实现方法 1. **PHP** ```php <?php $encoded = "https%3A%%2F%2Fwww.example.com%2F%3Fname%3DJohn%20Doe%26age%3D25"; $decoded = urldecode($encoded); echo "Decoded URL: " . $decoded; // 输出:https://www.example.com/?name=John Doe&age=25 ?> ``` *特点*:`urldecode()`函数自动处理`+`和`%20`均转为空格[^1]。 2. **Java** ```java import java.net.URLDecoder; public class Main { public static void main(String[] args) throws Exception { String encoded = "https%3A%2F%2Fwww.example.com%2F%E4%BD%A0%E5%A5%BD"; String decoded = URLDecoder.decode(encoded, "UTF-8"); System.out.println("Decoded URL: " + decoded); // 输出:https://www.example.com/你好 } } ``` *注意*:必须显式指定字符编码(如UTF-8)[^2][^3]。 3. **Python** ```python from urllib.parse import unquote encoded = "https%3A%2F%2Fwww.example.com%2F%3Fq%3D%E6%B5%8B%E8%AF%95" decoded = unquote(encoded) print(f"Decoded URL: {decoded}") # 输出:https://www.example.com/?q=测试 ``` *Python 3特有*:`unquote()`支持嵌套解码。 4. **JavaScript** ```javascript const encoded = "https%3A%2F%2Fwww.example.com%2F%3Fcity%3D%E5%8C%97%E4%BA%AC"; const decoded = decodeURIComponent(encoded); console.log(decoded); // 输出:https://www.example.com/?city=北京 ``` *对比*:`decodeURI()`不解码`#`等保留字符,而`decodeURIComponent()`解码全部字符。 5. **C语言** ```c #include <stdio.h> #include <stdlib.h> char* url_decode(const char* src) { char* decoded = malloc(strlen(src) + 1); char* p = decoded; while (*src) { if (*src == '%' && isxdigit(*(src+1)) && isxdigit(*(src+2))) { *p++ = strtol(src+1, NULL, 16); src += 3; } else { *p++ = *src++; } } *p = '\0'; return decoded; } int main() { char* decoded = url_decode("https%3A%2F%2Fwww.example.com%2F"); printf("%s", decoded); // 输出:https://www.example.com/ free(decoded); return 0; } ``` *注意*:需手动处理内存分配和释放。 #### 二、关键注意事项 1. **编码一致性**:编解码必须使用相同字符集(如UTF-8) 2. **空格处理**:`+`和`%20`在不同语言中的默认行为不同 3. **多次解码**:避免对已解码字符串重复操作
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值