Create WordPress like slugs in PHP

This is an quick tutorial. I will show you how we can create perfect WordPress like slugs in php using just few lines of code. Have a look at the php function below.

function create_slug($title) {

	$slug = preg_replace('/[\s-]+/', '-', trim($title));
	$slug = preg_replace('/[^a-z0-9-]/', '', strtolower($slug));

	return $slug;


Let’s understand how we are creating the slug from a title passed to this function. Firstly, all the white spaces are converted to hyphens(-)and then all other characters are removed except letters, numbers, and hyphens. That is all we have to do to create a perfect slug for our pages.

Leave a Comment.