[英]Need help modifying these simple regular expressions to match urls
我正在小型MVC框架中構建路由器對象。 它解析URL字符串以發現控制器,動作等。它是可配置的。
當前,用戶可以通過傳遞如下字符串來創建路由:
$this->connect('/:controller/:action/*');
$this->connect('/:controller', array('action' => 'index'));
$this->connect('/', array('controller' => 'static_pages', 'action' => 'index'));
路由器根據這些規則構建以下正則表達式:
#^(.*)/(.*)/?.*/?$#
#^(.*)/?$#
#^/$#
最后,路由器嘗試根據URL選擇正確的路由。 上述路線的網址如下所示:
/cars/get_colors/ # will invoke cars->get_colors();
/cars/ # will invoke cars->index();
/ # will invoke static_pages->index();
我的正則表達式不正確。 第一個(更具體的)表達式可以匹配第二個條件,第二個表達式可以匹配第一個條件。
如果我翻轉順序以進行反向檢查,則靜態頁面路由有效,而控制器索引路由有效,但控制器索引rout捕獲所有更具體的路由!
我使用正則表達式是因為用戶還可以連接以下路由:
$this->connect('/car/:action/*', array('controller' => 'cars');
$this->connect('/crazy/url/:controller/:action/*');
它將構建兩個類似於此的正則表達式:
#^car/(.*)/?.*/?$#
#^crazy/url/(.*)/(.*)/?.*?$#
最后,執行以下路由:
/car/get_colors/ # will invoke cars->get_colors();
/crazy/url/cars/get_colors/ # will invoke cars->get_colors();
首先,可以使用explode函數將URL拆分為多個段,而根本不使用正則表達式,從而使您的生活更輕松。
但是,如果必須使用正則表達式,請將“。*”更改為“ [^ /] +”
請記住,點匹配所有內容,包括斜杠。 表達式“ [^ /]”匹配除斜杠之外的所有內容。
另外,如果字符串以斜杠開頭,則需要以正斜杠開頭。
最后,您需要使用“ +”號而不是“ *”號。
考慮以下示例,它們與您帖子中的正則表達式相對應:
#^/[^/]+/[^/]+(/.*)?$#
#^/[^/]+/?$#
#^/$#
#^/car/[^/]+(/.*)?$#
#^/crazy/url/[^/]+/[^/]+(/.*)?$#
我已經使用preg_replace函數來做到這一點。
preg_replace($ pattern,$ replacement,$ string)
preg_replace函數執行正則表達式搜索和替換。 這將在主題中搜索要匹配的圖案並將其替換為替換。
例如http://example.com/my-planet-earth/
我說的是格式化“我的地球”。 在這里,$ string可以是“我的地球”,而$ urlKey可以是“ my-planet-earth”。$ string =“ planet + *&john doe / / \\ \\ ^ 44 5%6 +-@ ku!〜`this” ; $ urlKey = preg_replace(array('/ [^ a-z0-9-] / i','/ [] {2,} /','/ [] /'),array('','',' -'),$ string); //輸出:planet-john-doe-44-5-6 --- ku-this
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.