Replace all characters that aren’t letters and numbers with a hyphen [duplicate]

This should do what you’re looking for: function clean($string) { $string = str_replace(‘ ‘, ‘-‘, $string); // Replaces all spaces with hyphens. return preg_replace(‘/[^A-Za-z0-9\-]/’, ”, $string); // Removes special chars. } Usage: echo clean(‘a|”bc!@£de^&$f g’); Will output: abcdef-g Edit: Hey, just a quick question, how can I prevent multiple hyphens from being next to each … Read more

Using slugs in codeigniter

I just store the slugs in my database table, in a column called slug, then find a post with the slug, like this: 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, … Read more

How to convert a Title to a URL slug in jQuery?

I have no idea where the ‘slug’ term came from, but here we go: function convertToSlug(Text) { return Text.toLowerCase() .replace(/ /g, ‘-‘) .replace(/[^\w-]+/g, ”); } The first replace method will change spaces to hyphens, second, replace removes anything not alphanumeric, underscore, or hyphen. If you don’t want things “like – this” turning into “like—this” then … Read more

How do I create a slug in Django?

You will need to use the slugify function. >>> from django.template.defaultfilters import slugify >>> slugify(“b b b b”) u’b-b-b-b’ >>> You can call slugify automatically by overriding the save method: class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() def save(self, *args, **kwargs): self.s = slugify(self.q) super(Test, self).save(*args, **kwargs) Be aware that the above will cause … Read more

String slugification in Python

There is a python package named python-slugify, which does a pretty good job of slugifying: pip install python-slugify Works like this: from slugify import slugify txt = “This is a test —” r = slugify(txt) self.assertEquals(r, “this-is-a-test”) txt = “This — is a ## test —” r = slugify(txt) self.assertEquals(r, “this-is-a-test”) txt=”C\”est déjà l\’été.’ r … Read more

How can I create a friendly URL in ASP.NET MVC?

There are two steps to solve this problem. First, create a new route or change the default route to accept an additional parameter: routes.MapRoute( “Default”, // Route name “{controller}/{action}/{id}/{ignoreThisBit}”, new { controller = “Home”, action = “Index”, id = “”, ignoreThisBit = “”} // Parameter defaults ) Now you can type whatever you want to … Read more