php 在 codeigniter 中使用 slug
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3305786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using slugs in codeigniter
提问by esafwan
I have heard of people using slugs for generating clean urls. I have no idea how it works. Currently i have a codeigniter site which generates url's like this
我听说有人使用 slugs 来生成干净的 url。我不知道它是如何工作的。目前我有一个 codeigniter 网站,它生成这样的网址
www.site.com/index.php/blog/view/7
From what i understand by maintaining a slug field it is possible to achieve urls like
根据我的理解,通过维护一个 slug 字段可以实现像
www.site.com/index.php/blog/view/once-upon-a-time
How is this done? Especially in reference to codeigniter?
这是怎么做的?特别是在参考 codeigniter 时?
回答by BoltClock
I just store the slugs in my database table, in a column called slug, then find a post with the slug, like this:
我只是将 slug 存储在我的数据库表中的一个名为 的列中slug,然后找到一个包含 slug 的帖子,如下所示:
public function view($slug)
{
$query = $this->db->get_where('posts', array('slug' => $slug), 1);
// Fetch the post row, display the post view, etc...
}
Also, to easily derive a slug from your post title, just use url_title()of the URL helper:
此外,要轻松地从您的帖子标题中获取 slug,只需使用url_title()URL 助手:
// Use dashes to separate words;
// third param is true to change all letters to lowercase
$slug = url_title($title, 'dash', true);
A little bonus: you may wish to implement a unique key constraint to the slugcolumn, that ensures that each post has a unique slug so it's not ambiguous which post CodeIgniter should look for. Of course, you should probably be giving your posts unique titles in the first place, but putting that in place enforcesthe rule and prevents your application from screwing up.
一个小好处:您可能希望对列实施唯一的键约束slug,以确保每个帖子都有一个唯一的 slug,因此 CodeIgniter 应该查找哪个帖子就不会产生歧义。当然,您可能应该首先为您的帖子指定唯一的标题,但将其设置到位会强制执行规则并防止您的应用程序出错。
回答by alpere
You can use the CI Slug Library by Eric Barnes:
您可以使用 Eric Barnes 的 CI Slug 库:
回答by Italo Hernández
To my ES friends, remove accented characters using this, from Text Helper:
对于我的 ES 朋友,使用它从文本助手中删除重音字符:
$string = 'áéíóú áéíóú';
$slug = url_title(convert_accented_characters($string), 'dash', true));
echo $slug; //aeiou-AEIOU

