簡體   English   中英

codeigniter 3 URI 路由 - 從給定的 url 獲取右側

[英]codeigniter 3 URI routing - geting right hand side from given url

我需要在 Codeigniter 3 中模擬路由,所以我的問題是如何以編程方式從任何 URL 獲取右側?

例如,我有一些路線:

$route["blog"] = "Main/blog/en";
$route["blog/(:any)"] = "Main/blog/en/$1";
$route["novosti"] = "Main/blog/sr";
$route["novosti/(:any)"] = "Main/blog/sr/$1";
$route["contact"] = "Main/contact/en";
$route["kontakt"] = "Main/contact/sr";

現在我需要一個 function 可以返回給定 URL 部分的右側,如下所示:

echo $this->route->item("novosti/petar")

然后應該打印 Main/blog/sr/$1 或 Main/blog/sr/petar

Codeigniter中是否有這樣的function,因為我在文檔中找不到?

更新:我正在查看整個系統/路由器 class 並且我看到受保護的 function _parse_routes 正在做類似的事情,所以如果沒有 function,我可以根據需要創建一個。

用這個

$this->router->routes['blog']

你會得到

Main/blog/en

Codeigniter is simple, too simple... And because it is not obvious for me where that function is (if exists at all) I've just adopted _parse_routes to parse URL (slug) into the right-hand side from which I can find相應的文件容易得多。

就是這樣(如果有人遇到與我相同的情況)。

  function parseRoute($uri) {

    // Get HTTP verb
    $http_verb = isset($_SERVER['REQUEST_METHOD']) ? strtolower($_SERVER['REQUEST_METHOD']) : 'cli';

    // Loop through the route array looking for wildcards
    foreach ($this->router->routes as $key => $val) {
      // Check if route format is using HTTP verbs
      if (is_array($val)) {
        $val = array_change_key_case($val, CASE_LOWER);
        if (isset($val[$http_verb])) {
          $val = $val[$http_verb];
        } else {
          continue;
        }
      }

      // Convert wildcards to RegEx
      $key = str_replace(array(':any', ':num'), array('[^/]+', '[0-9]+'), $key);

      // Does the RegEx match?
      if (preg_match('#^' . $key . '$#', $uri, $matches)) {
        // Are we using callbacks to process back-references?
        if (!is_string($val) && is_callable($val)) {
          // Remove the original string from the matches array.
          array_shift($matches);

          // Execute the callback using the values in matches as its parameters.
          $val = call_user_func_array($val, $matches);
        }
        // Are we using the default routing method for back-references?
        elseif (strpos($val, '$') !== FALSE && strpos($key, '(') !== FALSE) {
          $val = preg_replace('#^' . $key . '$#', $val, $uri);
        }

        return $val;
      }
    }

    // If we got this far it means we didn't encounter a
    // matching route so we'll set the site default route
    return null;
  }

現在,這個:

echo parseRoute("novosti/petar")

將產生:

Main/blog/sr/petar

又名:控制器 class / function 里面的 controller / 語言參數 / 博客文章

您可以使用以下代碼獲取所需的信息。

$this->router->routes['novosti/(:any)'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM