2015-03-02 19 views
0

我想作一個正則表達式路線參數,這是我的路由文件路由文件的URL參數:Symfony2中:如何做一個正則表達式中,以使清潔URL名稱

editBatiments: 
    path:  /mypathto/edit/{name} 
    defaults: { _controller: MyBundle:Mycontroller:editBatiments } 
    requirements: 
     name: // put the regex here 
    methods: GET 

這個正則表達式適用於刪除空間,下劃線,標點符號。但我想允許大寫和course.In事實上小寫當我進行的路線,我的網址是這樣的:

localhost/myFolder/mypathTo/edit/Name%20Of%20My%20Bâtiment 

我想刪除「%20」和空間,以有這樣的網址:

localhost/myFolder/mypathTo/edit/NameOfMyBâtiment 

我怎麼能爲了繼續有乾淨的網址是什麼?

我試試這個:

#route file 
    editBatiments: 
     path:  /mypathto/edit/{name} 
     defaults: { _controller: MyBundle:Mycontroller:editBatiments } 
     requirements: 
      name: "[a-zA-Z0-9-_\/-\s.]+" 
     methods: GET 

但我有此錯誤:

An exception has been thrown during the rendering of a template ("Warning: preg_match(): Compilation failed: invalid range in character class at offset 16 in C:\wamp\www\MyFolder\app\cache\dev\classes.php line 848") in MyBundle:MyFolder:indexBatiments.html.twig at line 60.

這是indexBatiments.html.twig at line 60代碼:

<td> 
    <a href="{{ path('editBatiments', {'name': batiment.name}) }}"> 
    <button class="btn btn-warning btn-xs">Edit</button> 
    </a> 
</td> 

有人可以幫助我,以使當我繼續這條路線時,是一個長長的網址?

預先感謝您。

回答

1

您正則表達式更改爲:

name: "[a-zA-Z0-9_\/\s.-]+" 

即保持字符類連字符轉義爲最後一個字符或者第一個字符。請注意,字符類中間的未轉義的連字符會被視爲範圍,因此會導致出現異常。

PS:您可以縮短你的正則表達式來:

name: "[\w\/\s.-]+" 

編輯:你看上去也匹配的Unicode文本。試試這個正則表達式

name: "[\\p{L}\\p{N}/\\s.-]+" 
+1

@anabhava,我試試你的解決方案,但我有這個錯誤太:'一個例外模板(「參數‘名稱的呈現’路由‘editBatiments期間已經拋出’必須匹配」 [a-zA-Z0-9 -_/\ s .-] +「(」BâtimentA「given給出)來生成相應的URL。」)在MyBundle:MyFolder:indexBatiments.html.twig在第60行。事實上,當我點擊編輯按鈕時,路線渲染一個表單,我可以在其中編輯我選擇的Bâtiment。我的路線中的url參數是我選擇的這個bâtiment的名字。 – 2015-03-02 10:16:30

+4

@french_dev,也許你需要在indexBatiment.html.twig中通過第60行的要求? – 2015-03-02 10:18:49

+0

如果您獲得**必須匹配'「[a-zA-Z0-9 -_/\ s。 - ] +「'**這意味着你仍然不會使用我建議的正則表達式 – anubhava 2015-03-02 10:21:58