How to Create User Friendly URLs or Slugs with PHP

x theme
(Last Updated On: July 10, 2014)

If you’re creating a blog with custom PHP, you might need a way to create user friendly urls or slugs with PHP. Here we’ll show a simple method to create a user friendly url or slug with PHP.

We will create a function and use PHP’s “preg_replace()” function to make the URL user friendly. Benefit of using function is that we can call it anywhere without writing the code again and again.

In the script, we will take a title of a post, let’s say, “This is example post“, and will convert it to the user friendly url or slug “this-is-example-post“.

//Function for creating slugs
function create_slug($string){
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return $slug;

//Using the function
$title = "This is example post";
$slug = create_slug($title);

echo $slug; // this-is-example-post

About the author


Leave a Reply

Your email address will not be published. Required fields are marked *