Search code examples
phpcakephpspecial-charactersslugcakephp-1.2

Remove special characters and convert vowels with accent marks to vowels without accent marks in CakePHP slugs


I need two improvements for my slugs:

  1. Removing special characters.

  2. Converting vowels with accent marks to vowels without accent marks.

The problem is that my website is generating URLs with slugs such as:

https://example.net/Toronto/product/férula-dental-limpieza-con-ul

https://cuponclub.net/Toronto/product/lifting-de-pestañas

Those special characters such as "é" and "ñ" in the URL tend to be problematic for me for many different reasons such as when I integrate URLs to APIs that I use or even when sharing links...

I am using CakePHP 1.2. This is how I implement the slugs in the code:

class Product extends AppModel{
    ..........
    ..........
    ..........
    var $actsAs = array(
        'Sluggable' => array(
            'label' => array(
                'short_name'
            ),
            'length' => 30,
            'overwrite' => false
        )
    );
    ..........
    ..........
    ..........
}

In the database, 'short_name' is the field that is used to generate the slug. Without CakePHP, PHP already provides built-in functions such as str_replace() and preg_replace() and by using those functions and a regular expresion such as [^A-Za-z0-9\-], I could remove all special characters after replacing all spaces with hyphens. But since I am using CakePHP, I need to use its syntax. I was reading https://github.com/msadouni/cakephp-sluggable-plugin and I found this information about the label:

label : (array | string, optional) set to the field name that contains the string from where to generate the slug, or a set of field names to concatenate for generating the slug. DEFAULTS TO: title

Can I treat label as a string and apply functions such as str_replace() and preg_replace() to it?


Solution

  • Given that the plugin that you are using hasn't had any updates in the last 10 years, I would say it's safe to assume that maintaining it yourself is your best option - if you don't want to create a behavior from scratch that is, wich shouldn't be very hard to do either

    So, just fork it and make the required changes or create a custom behavior. I would also suggest to have a look at how the latest CakePHP handles this, see the source for \Cake\Utility\Text::slug(). If your PHP installation supports it, then you may want to backport this, ie make use of PHPs transliteration functionality provided by the INTL extension.