簡體   English   中英

Php:使用正則表達式匹配 url,如果模式匹配則提取值

[英]Php : match url using regex and extract values if pattern matches

嗨,我正在 php 中學習動態 url 以創建自定義路由器

我使用這種方法設置路線

$router->get("/home",function(){
echo "this is home";
});

之前沒想到get()的第一個參數(我的router path)也可以寫成/profile/{user}/id/{id}我試過在get()中用regex作為路徑,用preg匹配返回值但對 output 不滿意,因為每次我設置新路線時它都需要正則表達式

我想知道我將如何簡單地設置路由,如/profile/{user}/id/{id}/profile/{var: user}/id/{int: id}並獲得 output 就像路由-模式匹配返回一個包含鍵值的數組,其中鍵是用戶,值來自字符串等

定義路線:請求路線:output

/home                   form action : /home                     o/p = array()
/home/{page}            form action : /home/about               o/p = array(page=>'about')
/profile/{name}/id/{id} form action : /profile/stackuser/id/200 o/p = array(name=>stackuser,id=>200)

您可以使用命名的捕獲組將您的路線轉換為正則表達式:

$routes = [
  '/profile/{user}/id/{id}',
  '/this/will/not/match/for/sure',
];

$routes_regexps = array_map(
  function($route){
    return 
      '#^' // RE delimiter and a string start 
        /* Translate 
          {something}
          substrings into regexp named matches like
          (?<something>[^/]+)
        */
      . preg_replace("/\{(.*?)\}/", '(?<$1>[^/]+?)', $route) 
      . '$#' ; // String end and a RE delimiter
  }, 
  $routes
);

然后通過這些 RE 匹配 URL 路徑:

$test_urls = [
  '/profile/some_username/id/25',
  '/this/will/not/match'
];

foreach( $routes_regexps as $i => $re ){

  print "Route is: {$routes[$i]}\n";
  print "RE is: $re\n";

  foreach( $test_urls as $url ){

    $matches = [];
    if( preg_match_all($re,$url,$matches) ){
      
      print "Url [$url] did match the route, variables are: \n";
      print "User: {$matches['user'][0]}\n";
      print "id: {$matches['id'][0]}\n";

    } else {
      print "Url [$url] didn't match\n";
    }  

  }
}

但我更喜歡的方式是將路由和 URL 路徑轉換為 arrays 並逐個元素進行比較,檢查路由組件是否類似於{variable name here}

暫無
暫無

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

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