french_dev
french_dev

Reputation: 2177

Symfony2 : how to make a Regex in routing file for url argument in order to make clean url name

I would like to make a regex for a route argument, this my route file:

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

This regex is for delete space, underscore, punctuation. But I want to allow uppercase and lowercase of course.In fact when i proceed the route, my url looks like this:

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

I would like to delete "%20" and space in order to have an url like this:

localhost/myFolder/mypathTo/edit/NameOfMyBâtiment

How can i proceed in order to have clean url?

I try this:

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

But i have this error:

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.

this is the code in 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>

Someone could help me in order to make a cean url when I proceed this route?

Thank you in advance.

Upvotes: 0

Views: 1846

Answers (1)

anubhava
anubhava

Reputation: 785108

Change your regex to:

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

i.e. keep unescaped hyphen as last character or first character in character class. Note that an unescaped hyphen in the middle of a character class is treated as range hence causing the exception you're getting.

PS: You can shorten your regex to:

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

EDIT: Looks like you're also matching unicode texts. Try this regex

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

Upvotes: 1

Related Questions