2017-01-17 35 views
0

我有添加帖子表單來添加新帖子。我已將post職位視爲post_url或slug。我想要獨特的post_url。
以下是我迄今所做的 -使用職位標題創建獨特的slu 012

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

我得到輸出 -

的URL後

的URL後1

-URL-後1-1

post-url-1-1-1

但我想輸出 -

的URL後

的URL後1

的URL後2

的URL後3

我的代碼中有什麼問題?
請幫幫我。
謝謝。

+0

第一個變化$ POST_URL = ' - '。 $最大;到$ post_url = $ post_url。 $最大; – coder

+0

@coder它只是刪除連字符( - )並顯示輸出爲後URL,post-url1,post-url2 – Deepak

+0

plz檢查ans。 – coder

回答

2

更改代碼以下列方式

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

@ coder這正是我想要的。非常感謝。 – Deepak

3
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; 
}