我想为我的文章获得独特的slu ..我正在使用codeigniter。我想知道有一些像sample-title-1
和sample-title-2
这样的东西,如果有两篇文章具有相同的标题,例如codeignier对文件上传filename(:num)
的影响。我无法想办法做到这一点。我不是codeigniter的专家。我正在学习它。
我准备了一个函数,当传递一个字符串$str
时,它检查slug是否存在,如果存在,它会将该文章的ID
添加到该slug的末尾并返回它,如果不,它会返回slu ..
它工作正常,服务于独特的slug的目的。但我想要的是sample-title-1
和sample-title-2
之类的东西。有没有办法这样做?
$data['slug'] = $this->get_slug($data['title']);
public function get_slug ($str)
{
$slug = url_title($str, 'dash', true);
// Do NOT validate if slug already exists
// UNLESS it's the slug for the current page
$id = $this->uri->segment(4);
$this->db->where('slug', $slug);
! $id || $this->db->where('id !=', $id);
$category = $this->category_m->get();
if (count($category)) {
return $slug.$id;
}
return $slug;
}
答案 0 :(得分:1)
易于使用且真正有助于创建独特的slu have,CI slug library
阅读其文档以实现它。
答案 1 :(得分:0)
我以前做的就是制作slug db field UNIQUE
。
然后使用CI助手Url Helper和Text Helper
轻松完成所有操作 $last_id_inserted = //get from db the last post's ID;
$post_title = "My slug would be";
$slug = mb_strtolower(url_title(convert_accented_characters($post_title))).'-'.$last_id_inserted;
echo $slug;
//outputting my-slug-would-be-123
//insert the new post with slug
所以ID也是独一无二的,也是slu。的。
答案 2 :(得分:0)
我认为你需要这样的东西:
//Database loaded
//Text helper loaded
function post_uniq_slug($slug, $separator='-', $increment_number_at_end=FALSE) {
//check if the last char is a number
//that could break this script if we don't handle it
$last_char_is_number = is_numeric($slug[strlen($slug)-1]);
//add a point to this slug if needed to prevent number collision..
$slug = $slug. ($last_char_is_number && $increment_number_at_end? '.':'');
//if slug exists already, increment it
$i=0;
$limit = 20; //for security reason
while( get_instance()->db->where('slug', $slug)->count_all_results('posts') != 0) {
//increment the slug
$slug = increment_string($slug, $separator);
if($i > $limit) {
//break;
return FALSE;
}
$i++;
}
//so now we have unique slug
//remove the dot create because number collision
if($last_char_is_number && $increment_number_at_end) $slug = str_replace('.','', $slug);
return $slug;
}
实例:
post_uniq_slug('sample'); //"sample" exists
//sample-1
post_uniq_slug('sample-2013'); //"sample-2013" exists
//sample-2013-2
post_uniq_slug('sample-2013', '-', TRUE); //increment "sample-2013"
//sample-2014
*未经测试
答案 3 :(得分:0)
public function create_slug($name)
{
$table='tradeshow'; //Write table name
$field='slug'; //Write field name
$slug = $name; //Write title for slug
$slug = url_title($name);
$key=NULL;
$value=NULL;
$i = 0;
$params = array ();
$params[$field] = $slug;
if($key)$params["$key !="] = $value;
while ($this->db->from($table)->where($params)->get()->num_rows())
{
if (!preg_match ('/-{1}[0-9]+$/', $slug ))
$slug .= '-' . ++$i;
else
$slug = preg_replace ('/[0-9]+$/', ++$i, $slug );
$params [$field] = $slug;
}
return $alias=$slug;}