Create a URL Slug from any string in PHP.

In this blog, we will discuss the URL slug. we will see how can we generate or create a URL slug from any string in PHP.
As we all know that creating a user-friendly URL is an essential part of any website.
URL slug is also one of the main keys for the SEO of any web page. It helps the visitors to assure that the website is correct. Let’s take the following URL:

http://www.demosite.com/this is the example demo page

It will be rendered to the browser like this:

http://www.demosite.com/this%20is%20the%20example%20demo%20page

So, you can see, that the URL above can’t be considered a user-friendly one. Hence, it is necessary to interchange the spaces with hyphens. Here is how it can be done. Let’s see the example below:

<?php
function generateUrlSlug($urlString){
   $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $urlString);
   return $slug;
}

echo generateUrlSlug('this is the example demo page');
// This will return 'this-is-the-example-demo-page'

?>

OUTPUT : this-is-the-example-demo-page

So, thanks for following this blog, and if you need any help please leave your queries in the comment box we will be happy to help you.

Create a URL Slug from any string in PHP.expoundsofttechsolution

ghb