Welcome!

My name is Manmohanjit Singh and I’m 15 this year. Sorry you’ll just have to accept it, I may be a kid to you but trust me I’m not. I live in Malaysia and I go to school at SMK USJ 12. Read more...

Twitter

  • Loading...

@manmohanjit

Recent Tracks

  • Loading...

manmohanjit1

# Perfect function to create a readable slug with PHP

by Manmohanjit Singh on Jun 8th, 2010 in Code.

If you’re in the process of building a new custom CMS, you might want those clean shiny URL’s(or slugs). You can’t have spaces in it, neither can you have funny looking symbols. You also need to make sure its readable. After reading an article at Intrepid and at cubiq.org, I merged both those functions(that were provided) into one that would generate a perfect readable slug using PHP.

Here’s the PHP function to do so:

function create_slug($str) {
	$result = @iconv('UTF-8', 'ASCII//TRANSLIT', $str);
	$result = strtolower($result);
	$result = preg_replace("/[^a-z0-9\s-]/", "", $result);
	$result = trim(preg_replace("/\s+/", " ", $result));
	$result = preg_replace("/\s/", "-", $result);
	$result = preg_replace("/[\/_|+ -]+/", '-', $result);
	return $result;
}

This is the slug generated for this post title:

perfect-function-to-create-a-readable-slug-with-php

Tags:

No comments

  • No comments yet...

Leave A Comment

I'm watching you, please be nice and try not to spam. Comments are moderated. You can paste links directly, it will be formatted automatically. Basic XHTML tags are allowed.

Oh, I almost forgot. Comments are powered by Ajax, so don't hit the submit button twice. Thanks!

Wait for 15 seconds...