我有一个添加帖子表单来添加新帖子。我把帖子标题作为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;
我的输出为 -
-URL交
-URL后1
-URL后1-1
-URL后1-1-1
但我希望输出为 -
-URL交
-URL后1
-URL后2
-URL后3
我的代码中有什么问题?
请帮帮我
感谢。
答案 0 :(得分: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;
}
答案 1 :(得分: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;