IT & Programming

Create slug with PHP

  • How to create valid slug url with PHP.
  • Create SEO Friendly url with custom PHP function.

Function accepts a string parameters and returns valid url. It removes all characters from the string which are not supported by url.

Function

function generateSlug($phrase) {

    $result = strtolower($phrase);
    $result = str_replace(array('/', '-', '+', '.', '&', '&'), ' ', $result);
    $result = preg_replace("/[^a-z0-9s-]/", "", $result);
    $result = trim(preg_replace("/s+/", " ", $result));
    $result = trim(substr($result, 0, 45));
    $result = preg_replace("/s/", "-", $result);
    return $result;
}

Calling The Function

$phrase = "php/mysql tutorial";
echo generateSlug($phrase);

Output

php-mysql-tutorial

Comments

  1. Lakshman July 07, 2011

    Thank you salman

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *