Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Create URL Slug from Post Title

Regular expression function that replaces spaces between words with hyphens.

<?php
function create_slug($string){
   $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
   return $slug;
}
echo create_slug('does this thing work or not');
//returns 'does-this-thing-work-or-not'
?>

Comments

  1. Robin
    Permalink to comment#

    Maybe you can add a strtolower there?

  2. Dalibor Sojic
    Permalink to comment#

    Here is jquery (client side) slug creator.

    $('#title').change(function() {
    $(this).val($.trim($(this).val()));
    // Trim empty space

    $(this).val($(this).val().replace(/\s+/g,' '));
    // replace more then 1 space with only one

    $('#url').val($(this).val().toLowerCase());
    $('#url').val($('#url').val().replace(/\W/g, ' '));
    $('#url').val($.trim($('#url').val()));
    $('#url').val($('#url').val().replace(/\s+/g, '-'));
    });

  3. Benjamin Mayo
    Permalink to comment#

    Stop words are always a nice accompaniment to slug creators,

  4. Weblap.ro
    Permalink to comment#

    function remove_accent($str)
    {
    $a = array('À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','Ø','Ù','Ú','Û','Ü','Ý','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ø','ù','ú','û','ü','ý','ÿ','Ā','ā','Ă','ă','Ą','ą','Ć','ć','Ĉ','ĉ','Ċ','ċ','Č','č','Ď','ď','Đ','đ','Ē','ē','Ĕ','ĕ','Ė','ė','Ę','ę','Ě','ě','Ĝ','ĝ','Ğ','ğ','Ġ','ġ','Ģ','ģ','Ĥ','ĥ','Ħ','ħ','Ĩ','ĩ','Ī','ī','Ĭ','ĭ','Į','į','İ','ı','IJ','ij','Ĵ','ĵ','Ķ','ķ','Ĺ','ĺ','Ļ','ļ','Ľ','ľ','Ŀ','ŀ','Ł','ł','Ń','ń','Ņ','ņ','Ň','ň','ʼn','Ō','ō','Ŏ','ŏ','Ő','ő','Œ','œ','Ŕ','ŕ','Ŗ','ŗ','Ř','ř','Ś','ś','Ŝ','ŝ','Ş','ş','Š','š','Ţ','ţ','Ť','ť','Ŧ','ŧ','Ũ','ũ','Ū','ū','Ŭ','ŭ','Ů','ů','Ű','ű','Ų','ų','Ŵ','ŵ','Ŷ','ŷ','Ÿ','Ź','ź','Ż','ż','Ž','ž','ſ','ƒ','Ơ','ơ','Ư','ư','Ǎ','ǎ','Ǐ','ǐ','Ǒ','ǒ','Ǔ','ǔ','Ǖ','ǖ','Ǘ','ǘ','Ǚ','ǚ','Ǜ','ǜ','Ǻ','ǻ','Ǽ','ǽ','Ǿ','ǿ');
    $b = array('A','A','A','A','A','A','AE','C','E','E','E','E','I','I','I','I','D','N','O','O','O','O','O','O','U','U','U','U','Y','s','a','a','a','a','a','a','ae','c','e','e','e','e','i','i','i','i','n','o','o','o','o','o','o','u','u','u','u','y','y','A','a','A','a','A','a','C','c','C','c','C','c','C','c','D','d','D','d','E','e','E','e','E','e','E','e','E','e','G','g','G','g','G','g','G','g','H','h','H','h','I','i','I','i','I','i','I','i','I','i','IJ','ij','J','j','K','k','L','l','L','l','L','l','L','l','l','l','N','n','N','n','N','n','n','O','o','O','o','O','o','OE','oe','R','r','R','r','R','r','S','s','S','s','S','s','S','s','T','t','T','t','T','t','U','u','U','u','U','u','U','u','U','u','U','u','W','w','Y','y','Y','Z','z','Z','z','Z','z','s','f','O','o','U','u','A','a','I','i','O','o','U','u','U','u','U','u','U','u','U','u','A','a','AE','ae','O','o');
    return str_replace($a, $b, $str);
    }

    function post_slug($str)
    {
    return strtolower(preg_replace(array('/[^a-zA-Z0-9 -]/', '/[ -]+/', '/^-|-$/'), array('', '-', ''), remove_accent($str)));
    }

  5. Ant

    You would need also to remove punctuation symbols:

    $string = preg_replace( '/[«»“”!?,.]+/', '', $string );
  6. Asif Iqbal
    Permalink to comment#

    Its quite simple and good. Nice effort I must say.. I had also written one post for ASP Classic for same topic.

    How to: Create SEO Friednly URL in ASP Classic

    Thanks!

  7. Sudeep Sakalle
    Permalink to comment#

    Excellent post ! very simple and good.

    Thanks for putting it online.

    @Weblap.ro Thanks for this special char. removal script. This makes this page very useful.

    Sudeep
    Infovinity

  8. Seebz

    Another equivalent function that make better results : http://code.seebz.net/p/to-permalink/

  9. Devin
    Permalink to comment#

    This is the bees knees simple slug creation. Thank Chris!

  10. itechfan
    Permalink to comment#

    how to make post slug when you language is utf-8 like “xin chào”. i don’t want to change like “xin cho” when i use your function.

    My function like you:

    
    function remove_accent($str) 
    { 
      $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň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 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o'); 
      return str_replace($a, $b, $str); 
    } 
    
    function post_slug($str) 
    { 
      return strtolower(preg_replace(array('/[^a-zA-Z0-9 -]/', '/[ -]+/', '/^-|-$/'), 
      array('', '-', ''), remove_accent($str))); 
    } 
    

    Help me make change slug like string: “xin chào.”

    Thanks

    • Vincent Le
      Permalink to comment#

      For Vietnamese language I used this array:

      function remove_accent($str)
      {
      $a = array(
      'á','é','í','ó','ú','ý','Á','É','Í','Ó','Ú','Ý',
      'à','è','ì','ò','ù','ỳ','À','È','Ì','Ò','Ù','Ỳ',
      'ả','ẻ','ỉ','ỏ','ủ','ỷ','Ả','Ẻ','Ỉ','Ỏ','Ủ','Ỷ',
      'ã','ẽ','ĩ','õ','ũ','ỹ','Ã','Ẽ','Ĩ','Õ','Ũ','Ỹ',
      'ạ','ẹ','ị','ọ','ụ','ỵ','Ạ','Ẹ','Ị','Ọ','Ụ','Ỵ',
      'â','ê','ô','ư','Â','Ê','Ô','Ư',
      'ấ','ế','ố','ứ','Ấ','Ế','Ố','Ứ',
      'ầ','ề','ồ','ừ','Ầ','Ề','Ồ','Ừ',
      'ẩ','ể','ổ','ử','Ẩ','Ể','Ổ','Ử',
      'ậ','ệ','ộ','ự','Ậ','Ệ','Ộ','Ự'
      );
      $b = array(
      'a','e','i','o','u','y','A','E','I','O','U','Y',
      'a','e','i','o','u','y','A','E','I','O','U','Y',
      'a','e','i','o','u','y','A','E','I','O','U','Y',
      'a','e','i','o','u','y','A','E','I','O','U','Y',
      'a','e','i','o','u','y','A','E','I','O','U','Y',
      'a','e','o','u','A','E','O','U',
      'a','e','o','u','A','E','O','U',
      'a','e','o','u','A','E','O','U',
      'a','e','o','u','A','E','O','U',
      'a','e','o','u','A','E','O','U'
      );
      return str_replace($a, $b, $str);
      }

  11. tranh
    Permalink to comment#

    cool tips, but I can restrics duplicate slug

  12. Eric
    Permalink to comment#

    For the quick and not-so-dirty way I’ve always used:

    $slug = preg_replace(“/\W+/”,”-“,$text);

    By using \W+ you take care of all non-latin characters.

  13. Thomas
    Permalink to comment#

    No matter what I need done on a website I’m having trouble with I google what I want and your links never disappoint. Thanks Chris!

  14. Frenk
    Permalink to comment#

    How can i add a button? So when i click on Auto genrerator frienly url

  15. Shelly
    Permalink to comment#

    What about the built-in function for this? sanitize_title_with_dashes(); I use it all the time.

    • Rian Ariona
      Permalink to comment#

      sanitize_title_with_dashes() is wordpress function :).

  16. Shelly
    Permalink to comment#

    My bad! I thought you all were talking about WordPress :) Sorry!

  17. Davinder Singh
    Permalink to comment#
    function getSlug($text)
    { 
      $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
      $text = trim($text, '-');
      $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
      $text = strtolower($text);
      $text = preg_replace('~[^-\w]+~', '', $text);
      if (empty($text))
      {
        return 'n-a';
      }
      return $text;
    }
    

    100% working

  18. Karthikeyan K
    Permalink to comment#

    First of all thanks for this, snippet really solved my url problem.. :)

    Thanks a tonne…

  19. Chirag
    Permalink to comment#

    Thanx its really worth and work for me…:p

  20. Piotr Alexei
    Permalink to comment#

    Another way to do that simply :

    function text2url($string){
            $table = array(
                'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
                'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
                'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
                'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
                'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
                'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
                'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
                'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r', '/' => '-', ' ' => '-'
            );
            $text2url = strtolower(strtr($string, $table));
            $text2url = preg_replace('#[^0-9a-z]+#i', " ", $text2url);
            $text2url = str_replace(' ','-',trim($text2url));
            return $text2url;
        }
    
  21. Ladislav Janeček

    function slug($nadpis) {
    $url = $nadpis;
    $url = preg_replace(‘~[^\pL0-9_]+~u’, ‘-‘, $url);
    $url = trim($url, “-“);
    $url = iconv(“utf-8″, “us-ascii//TRANSLIT”, $url);
    $url = strtolower($url);
    $url = preg_replace(‘~[^-a-z0-9_]+~’, ”, $url);
    return $url;
    }

  22. AmirMasoud

    creating slug in this way is limited to English alphabets. it’s better to first use function explode and space as delimiter to convert to an array and then implode it with optional delimiter.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```