PHP Create Awesome Slugs

This is the function I use when creating slugs with PHP. It accepts a string and removes any special characters other than – and _

It will than replace spaces with dashes, underscores with dashes and double dashes with a single dash and finally returns makes the entire string lower case.


function createSlug($string){
	$slug = preg_replace("/[^a-zA-Z0-9 -_]/", "", $string);
	$slug = str_replace(array(" ","_","--"), "-", $slug);
	$slug = strtolower($slug);
	return $slug;


Example use:


$var = "Some Awesome Title!";	

echo createSlug($var); //returns some-awesome-title


This function will make SEF (search engine friendly) URL creation a snap!

Leave a comment

Show/Hide Footer Actions

Status: Available for your project.