Convert strings into slugs in php

While working with php, at some point we need to convert our strings into slugs for seo friendly urls or some other purpose. And our strings may contain different special characters.

To get rid of that characters and create a slug of that string use this function. It takes the string and return the seo friendly slug. Very simple but efficient.


  function slug($string){
    $string = strtolower(trim($string));
    $string = preg_replace('/[^a-z0-9-]/', '-', $string);
    $string = preg_replace('/-+/', "-", $string);
    return trim($string,"-");
  } 


Call function like this

$slug=slug("This is my title");

This is very helpful when we want to create urls based on some strings like create urls from post title.
Convert strings into slugs in php Convert strings into slugs in php Reviewed by JS Pixels on January 02, 2012 Rating: 5

3 comments:

  1. you can avoid the 2nd regexp:

    function slug($string) {
    return trim(preg_replace('/[^a-z0-9-]+/', '-', strtolower(trim($string))), "-");
    }

    ReplyDelete
    Replies
    1. @THELITTLEBUG
      The solution you suggested will remove only the leading and trailing dashes - and not from inside the text. The second regex is used to remove adjacent dashes in the string.

      Delete

Altaf Web. Powered by Blogger.