tags:

views:

36

answers:

2

I want to create slug URL's from a users title in my system.

If a user types "The best way's to get slim; period!", then I want the slug to be "the-best-ways-to-get-slim-period".

Also, if someone has already created a page with that title I want the slug to be "the-best-ways-to-get-slim-period-1".

My question is how can I check the database before a record is created? Ok, obviously I am going to have to perform a check in the database, and then a write. That's 2 queries. Is this the normal way to do it?

Also, are there any conventional regular expressions for filtering non alpha/number characters and replacing spaces with hyphens?

Any help is much appreciated.

Thanks.

A: 

To answer your first question:

Yes, you are going to need 2 queries/calls to the database. There's no other way of finding out whether a slug already exists or not. Obviously, if there's already a "1" post in there you can arrange your query to return all items so you know what number to use for your new slug.

select count(*) from slugTable where slugTitle
    like "the-best-ways-to-get-slim-period%"

(obviously this is only for illustrative purposes).

This will return 0 if the new slug is unique, or a positive value if there's any existing matches. You can use this count directly to set up your new slug:

if (selectCount > 0)
{
    slugURL = postTitle + "-" + selectCount;
}

(again pseudo code).

ChrisF
A: 

Over time I created this function for making slugs:

function filter($string)
{
    $search = array('`', '"', "'", ' ', '.');
    $replace = array('', '', '', '-', '-');

    $table = array(
        'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
        'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
        'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
        'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
        'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
        'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
        'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
        'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
    );

    $string = strtr($string, $table);

    $string = preg_replace('/[^a-zA-Z0-9_-]/', '-', $string);

    $string = preg_replace('/-+/', '-', $string);

    return trim($string, '-');
}

As for the first part, you'll need 2 queries.

robertbasic