Yii2 using hyphenated URLs in URL manager rules

When you're playing around with URL rules and you get the dreaded 404 message, there isn't very much help around. 

I recently used an action with two words in camel case like actionTestThis which, in Yii2, translates to a url like 'mycontroller/test-this'.

But if you've put in a special rule for this in your url manager, perhaps redirecting this to another controller

  'mycontroller/<action:\w+>' => 'mycontroller2/<action>',

You will, no doubt, get that lovely 404 message

This is because the regex \w relates to a single unhyphenated word.  To get around this, you have to change the regex to expect a hyphen.

  'mycontroller/<action:\w+(-\w+)*>' => 'mycontroller2/<action>'

As you will see from the regex pattern, this only allows for a group of 2 words like test-this but will not handle more like test-this-or-this

Any regex gurus out there?  How would you make that pattern a repeating pattern, if that's possible?

Did you know you can hire me?

I take on projects of all sizes. From Consulting to large Development Projects.

If you're starting a new Yii project and would like some help to get setup and running or you need some help with a particular module or you just need someone to develop the whole dang thing, then just ask ...

Leave a Comment

twitterfacebookgooglelinkedin https://me.yahoo.com