Tuesday 28 August 2012

Convert Title Into Slug URL Using PHP

During my job while uploading content for MPS project, i am always facing the same problem. Its always make me become lazious to change all link title into slugify format manually. I am weird why this new portal system can't handle this conversion.

To overcome this issues, i've created a new php code to assist my work. This is very basic code based on Regex pattern to remove all non alphanumeric character and change all spaces into dashes.

Here is what i want for this code:

1. Remove non alphanumeric chars.
2. Change spaces into dashes.
3. All must lowercase.

To fulfill above rule here the simplest code:

function slugify($txt)
{
  // replace all non alphanumeric into dashes
  $text = preg_replace('/\W+/', '-', $txt);

  // trim and lowercase
  return strtolower(trim($txt, '-'));
}
?>

Example scenario:

Mistery of Mine & How to : Extracting IP Values IPv6 2012 under 10% value

Will converted into:

mistery-of-mine-how-to-extracting-ip-values-ipv6-2012-under-10-value

Hope it help others.





No comments:

Post a Comment