2016-08-19 120 views
-1

我在嘗試學習如何將此URL寫入正則表達式模板以添加爲重寫時遇到問題。我已經試過各種正則表達式沙箱的數字出來我自己,但他們不會允許一個「/」例如,當我從這裏複製的表達式來進行測試:demoURL重寫正則表達式轉換

我有一個自定義後類型(出版物)與2分類學(雜誌,問題),我試圖創造一個漂亮的網址。

很多小時後,我來到這裏,瞭解如何將其轉換。

index.php?post_type=publications&magazine=test-mag&issue=2016-aug 

向模板的正則表達式的表達式(出版物雜誌問題是常數),可以輸出。

http://example.com/publications/test-mag/2016-aug/ 

希望有空間可以擴展,如果從該頁面跟隨一篇文章。

在此先感謝。

編輯1:

我得爲我的規則:

^publications/([^/]*)/([^/]*)/?$ 

,這對我的比賽:

^index.php?post_type=publications&magazine=$matches[1]&issue=$matches[2]$ 

和測試這一點:

http://localhost/publications/test-mag/2016-aug/ 

,但它給了我一個404.什麼問題?

+0

您將使用哪個URL重寫引擎? – 10100111001

+0

@ 10100111001 Wordpress rewrite – 4t0m1c

回答

1

^index\.php\?post_type=publications&magazine=([^&]+)&issue=([^&]+)$

  • ^開始
  • index\.php\?post_type=publications&magazine=文字文本
  • ([^&]+)一個或多個非符號字符(將得到所有文字到下一個URL參數,這是捕獲爲一組
  • &issue=字面文字
  • ([^&]+)一個或多個non-ampers和字符。串
+0

非常感謝,並且這些**([^&] +)**也可以作爲比賽的一種變量嗎? – 4t0m1c

+0

他們沒有。他們只是爲了讓你在代碼中分別獲得這些字符串。 – Whothehellisthat

+0

如何在重寫中回調這些字符串?對不起,我是完全新的正則表達式 – 4t0m1c

1
$str = 'index.php?post_type=publications&magazine=test-mag&issue=2016-aug'; 
preg_match('/magazine=([\w-]+?)&issue=([\w-]+)/', $str, $matches); 
$res = 'http://example.com/' . $matches[1] . '/' . $matches[2] . '/'; 
echo $res; // => http://example.com/test-mag/2016-aug/ 
1

也捕獲

  • $端可以使用WP重寫API在add_rewrite_rule的方法來做到這一點。

    add_rewrite_rule('^/([^/]*)/([^/]*)/?$','index.php?post_type=publications&magazine=$matches[1]&issue=$matches[2]','top');