Create URL slug with PHP

Create URL slug with PHP

Online by JSC0d3
June 24, 2014 | | 1379 recognitions

Having a user friendly URL is user important not just for SEO but also to help the visitors know that the website they are on is correct.

If you have spaces in your URL they will be replaced by %20 so if you are linking to the page.

http://www.domain.com/this is the sample page

The browser would actual render this URL as

http://www.domain.com/this%20is%20the%20sample%20page

As you can see this isn’t the most user friendly URL so you need to be able to replace the spaces with hyphens. Here is a PHP snippet that will replace all spaces with a hyphen.

Create url slug

function create_url_slug($string){
   $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
   return $slug;
}

echo create_url_slug('this is the sample page');
// This will return 'this-is-the-sample-page'

Extended URL Slug Version

Here is an extended version of the URL slug function. This will take care of any characters which have accents and will also catch double hyphens in the URL and replace it will just the one hyphen.

function slugify($str) {
    $search = array('Ș', 'Ț', 'ş', 'ţ', 'Ş', 'Ţ', 'ș', 'ț', 'î', 'â', 'ă', 'Î', 'Â', 'Ă', 'ë', 'Ë');
    $replace = array('s', 't', 's', 't', 's', 't', 's', 't', 'i', 'a', 'a', 'i', 'a', 'a', 'e', 'E');
    $str = str_ireplace($search, $replace, strtolower(trim($str)));
    $str = preg_replace('/[^\w\d\-\ ]/', '', $str);
    $str = str_replace(' ', '-', $str);
    return preg_replace('/\-{2,}', '-', $str);
}
JSC0d3's Logo
About JSC0d3

JSC0d3 is an entrepreneur, online marketer, and an employee of an IT company. When not building websites, creating content, or helping customers improve their online business, spend time with their wife and two beautiful children. Although he still feels new in WordPress, he enjoys sharing what he has learned with all of you! If you want to get in touch with him, you can do this through this website.

On the same idea

Posted by | February 9, 2019

WordPress' wp_link_pages() function, used for displaying page links in multi-page posts, lacks one big feature You can display a list of...

Posted by | December 14, 2018

Preliminary step: Testing whether the code complies with the format of a fiscal identification code (CIF) That is, the maximum length should be 10...

Posted by | November 8, 2017

Nowadays, a lot of bloggers choose to remove HTML tag from WordPress websites However, for beginners and newbies in this field, they may feel...

Previous PostBackNext Post

Leave here an impression