使用 post 的标题创建独特的 slug

Creating unique slug using title of post

我有一个添加 post 表单来添加新的 post。我已将 post 标题设为 post_url 或 slug。我想要独一无二的 post_url.
这是我到目前为止所做的 -

$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;

我得到的输出为 -

post-url

post-url-1

post-url-1-1

post-url-1-1-1

但我希望输出为 -

post-url

post-url-1

post-url-2

post-url-3

我的代码有什么问题?
请帮助我。
谢谢

按以下方式更改您的代码

$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;
function UniqueSlugGenerator($p){
    include("conn.php");
    $RowCou=0;
    $slug = preg_replace('/[^a-z0-9]/', '-', strtolower(trim(strip_tags($p))));
    $qq = mysqli_query($conn,"select Slug from ser_posts where Slug like '$slug%'") or die(mysqli_error($conn));
    $RowCou = mysqli_num_rows($qq);
    return ($RowCou > 0) ? $slug.'-'.(++$RowCou) : $slug;
}