Slugify strings

Published on and tagged with cakephp  feature

In a recent changeset a nice, little function has been introduced: Inflector::slug(). Such a function is used for example in blogs to create urls from titles.

Its usage is simple:

echo Inflector::slug('This is a test');
// outputs: This_is_a_test

echo Inflector::slug('This is a test', '-');
// outputs: This-is-a-test

You have to be careful with this function if you use it for example with german umlauts, as you may get an unexpected result:

echo Inflector::slug('Es sind Kühe auf der Wiese');
// outputs: Es_sind_K_he_auf_der_Wiese

8 comments baked

  • Beth

    I think you should help write the new 1.2 docs!!!

    This was a great find. And thanks for sticking around and writing about cake ;)

  • Tarique Sani

    This is a cool find, but I guess the utility is restricted to the English charset

  • Nik Chankov

    I’ve made such function myself 2 days ago :)
    It’s pretty simple to do it, but I hed some problem with non English characters. I have to test this one, but from the explanation it’s looking very good.

  • speedmax

    keep up the good work Daniel :)

  • cakebaker

    @all: Thanks for your comments!

    @Beth: Well, as I don’t agree with the way the documentation is developed it doesn’t make sense for me to help with the 1.2 docs. And another reason is that I no longer get credits for what I did for the 1.1 manual… So I better invest my time into other projects resp. this blog :)

    @Nik: As I showed with the German umlauts you may get an unexpected result when using non-English characters. But of course it is worth a test.

  • Felix

    Wow! So cool!

  • Pat

    It’s worth a look at how WordPress does this conversion — it accounts for encoding and everything. I’ve used that technique for many projects.

  • cakebaker

    @Pat: Thanks for the tip with WordPress. Do you know in which file this conversion happens?

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License