Dev

By Carlos Santana on
Reading time: 2 minutes

PHP-jSLxr.png

I used PHP a few years ago for a long time, but I noticed that PHP is still very popular, so I have the plan to share some functions/snippets I used when I was a PHP developer that I hope can be useful for you as well.

In this post, I want to show you how to create a slug function to improve our SEO, basically is a way to lower case the letters and replace the spaces with dashes (-), but most of the slug functions you will find on the internet they cannot handle special characters like Spanish accents or other types of characters, so I hope this can be useful for you.

function slug($str) {	
  // Converting special characters 
  $characters = array(
    "á" => "a", 
    "ç" => "c", 
    "é" => "e", 
    "í" => "i", 
    "ñ" => "n", 
    "ó" => "o", 
    "ú" => "u",
    "à" => "a", 
    "è" => "e", 
    "ì" => "i", 
    "ò" => "o", 
    "ù" => "u",
    "¿" => "",
    "¡" => ""
  );	

  $str = strtolower(trim(strtr($str, $characters)));	
  $str = preg_replace("/[^a-z0-9-]/", "-", $str);
  $str = preg_replace("/-+/", "-", $str);

  if (substr($str, strlen($str) - 1, strlen($str)) === "-") {
    $str = substr($str, 0, strlen($str) - 1);
  }

  return $str;
}

slug('Hello World!'); // hello-world
slug('¿Cuántos niños y niñas hay aquí?'); // In Spanish: cuantos-ninos-y-ninas-hay-aqui
avatarLeave a comment

Your comment

Only members can comment. You can Login or Sign Up