Search code examples
phpslug

Creating unique slug using title of post


I have an add post form to add new post. I have taken post title as post_url or slug. I want unique post_url.
Here is what I have done so far -

$post_name = $this->input->post('post_title');
function clean($post_name) {
    $name = trim($post_name);
    $post_name = str_replace(' ', '-', $name);
    return preg_replace('/[^A-Za-z0-9\-]/', '', $post_name);
}

$post_url = clean($post_name);
$query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'");
while ($r = mysql_fetch_assoc($query)) {
    $slugs[] = $r['post_url'];
    if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) {
        $max = 0;
        while (in_array(($post_url . '-' . ++$max), $slugs)) ;
        $post_url .= '-' . $max;
    }
}
echo "Slug " . $post_url;

I am getting output as -

post-url

post-url-1

post-url-1-1

post-url-1-1-1

But I want output as -

post-url

post-url-1

post-url-2

post-url-3

What is a problem in my code?
Please help me.
Thanks.


Solution

  • Change your code in the following way

    $post_url = clean($post_name);
    $post_url1 = $post_url;
    $query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'");
    while ($r = mysql_fetch_assoc($query)) {
        $slugs[] = $r['post_url'];
        if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) {
            $max = 0;
            $post_url = $post_url1;
            while (in_array(($post_url . '-' . ++$max), $slugs)) ;
            $post_url .= '-' . $max;
        }
    }
    echo "Slug " . $post_url;