Create URL Slug from Post Title using PHP

The following functions will helps to create search engine optimization url for the website. This will strip all the special characters and punctuation away from the URL and place hyphen in between each words.

For acheving the required results, used regular expression function that replaces spaces between words with hyphens and its remove the special characters from string or post title provided as input to fundtion.

Javascript function which helps to create slug url and place the created slug value in the given place holder.

[js]
/**
* Jquery stringToSlug plugin
* @param {Object} options
* Options will contains the trigger action on specified event and place holder for slugging text box.
*/
jQuery.fn.stringToSlug = function(options) {
var defaults = {
setEvents: ‘keyup keydown blur’, //set Events that your script will work
replace: ‘#permalink’
};

var opts = jQuery.extend(defaults, options);

jQuery(this).bind(defaults.setEvents, function () {
var stringToSlug = jQuery.trim(jQuery(this).val()).replace(/\s+/g,’-‘).replace(/[^a-zA-Z0-9\-]/g,”).toLowerCase().replace(/\-{2,}/g,’-‘);
jQuery(defaults.replace).val(stringToSlug);
return this;
});

return this;
};

$(document).ready(function() {
// You can define which textbox value need to create as slug and also event also you can provide in options
$("#Post_name").stringToSlug({replace: ‘#Post_link’});
// #Post_name is the ID of the textbox which contain string with / without special characters.
// #Post_link is the ID of the textbox to display the link generated based on the text given in #Post_name. #Post_link textbox should be read only, then only user will not update the link details.
});
[/js]

It is server side URL slug creation method, in this method also will strip all the special characters and punctuation away from the URL and place hyphen in between each words.

[php]
/**
* Create Slug from title
* @param $string
*/
function createSlug($string){
$slug = strtolower(preg_replace(array(‘/[^a-zA-Z0-9 -]/’, ‘/[ -]+/’, ‘/^-|-$/’), array(”, ‘-‘, ”), trim($string)));
return $slug;
}
[/php]

For example:
[php] echo createSlug(“US Dollar $ convertion into INR, $1 = RS. ?”); [/php]

output:
[code] us-dollar-convertion-into-inr-1-rs[/code]

Thanks for reading this post. Share your comments, which will help me to improve posting blog.

Permanent link to this article: https://blog.openshell.in/2014/08/create-url-slug-from-post-title-using-php/