Quelques fonctions pour avoir un slug parfait en PHP et JS

Cela fait maintenant plusieurs mois que j'essaye d'avoir des slug parfait sans bundle sous Symfony ou même en php native, j'avais mon petit bout de code personnalisé, mais qui était loin d'être parfait.

Je me suis donc mis à chercher sur le web des fonctions qui pouvait être intéressante et j'ai fini par trouver cette petite fonction très sympathique et simple à utiliser !

Version PHP :
 

function format_uri($string, $separator = '-')
    {
        $accents_regex = '~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i';
        $special_cases = array('&' => 'and', "'" => '');
        $string = mb_strtolower(trim($string), 'UTF-8');
        $string = str_replace(array_keys($special_cases), array_values($special_cases), $string);
        $string = preg_replace($accents_regex, '$1', htmlentities($string, ENT_QUOTES, 'UTF-8'));
        $string = preg_replace("/[^a-z0-9]/u", "$separator", $string);
        $string = preg_replace("/[$separator]+/u", "$separator", $string);
        return $string;
}

Pour l'utiliser voici un exemple :
 

//Symfony 
$this->format_uri($mavariable);

//PHP native
$slug = format_uri($mavariable);

 

Version Javascript :

function slugify(text) {
  const from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;"
  const to = "aaaaaeeeeeiiiiooooouuuunc------"

  const newText = text.split('').map(
    (letter, i) => letter.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)))

  return newText
    .toString()                     // Cast to string
    .toLowerCase()                  // Convert the string to lowercase letters
    .trim()                         // Remove whitespace from both sides of a string
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/&/g, '-y-')           // Replace & with 'and'
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-');        // Replace multiple - with single -
}


Pour l'utiliser voici un exemple :

let x = slugify(mavariable);


J'espère que ces fonctions vous pouvoir vous aidez dans vos projets !