tags:

views:

48

answers:

1

I am using only slug to identify a page on the website, like: example.tld/view/this-fancy-slug . This is generated from the title automatically with this function:

public static function Normalize($str)
{
    $charset = "UTF-8";
    $separator = "-";

    $str = strtolower(htmlentities($str, ENT_COMPAT, $charset));
    $str = preg_replace('/&(.)(acute|cedil|circ|lig|grave|ring|tilde|uml);/', "$1", $str);
    $str = preg_replace('/([^a-z0-9]+)/', $separator, html_entity_decode($str, ENT_COMPAT, $charset));
    $str = trim($str, $separator);

    return $str;
}

This returns a perfect slug... but I need unique slugs. So I've to combine with mysql to check if exists a slug that fits with the created. No problem with that.

The problem is that I want to add a -1 at the final if there is ONE slug. But can be buggy if are added 3 equal slugs so... how can I manage this to go from slug, slug-1, slug-2, slug-3... slug-100, slug-n?

Thank you in advance!

A: 

Hi,

Don't just check if that identical slug is present. Use a regular expression to count all the slugs that follow the pattern /(<base-regex-for-slug>)(-\d+)?/. Because you only allow alphanumerics your base regex above will be the slug itself.

Regards, Alin

Alin Purcaru
This function only gives me the title-as-slug. In another part, the MySQL queries, I'll have to check it. I don't know how to manage: check if slug returns a true, if returns, check what is the last number (NULL, -1, -2...).
Isern Palaus
That is exactly what I answered to. Make the function to return the number of times the slug was used. To make this you don't check for an exact match in SQL (LIKE or =) but check for a regular expression pattern (RLIKE). http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
Alin Purcaru
I didn't know about RLIKE! Thank you! :)
Isern Palaus
Sorry Alin, I'm having some troubles to implement it. Can you help me? I have two entries: "lorem" and "lorem-1" (as news.slug). I'm using: `SELECT id,slug FROM news WHERE slug RLIKE '/(lorem)(-\d+)?/'` and returns me 0 rows. I'm not doing it right? Thank you in advance!
Isern Palaus
Don't use /-es. http://dev.mysql.com/doc/refman/5.1/en/regexp.html
Alin Purcaru