Skip to content

Instantly share code, notes, and snippets.

@attitude
Last active May 7, 2021 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save attitude/9842170 to your computer and use it in GitHub Desktop.
Save attitude/9842170 to your computer and use it in GitHub Desktop.
Function to generate a slug (a normalized URL sanitized string)
{
"name": "attitude/generate_slug",
"autoload": {
"files": ["function-generate_slug.php"]
}
}
<?php
/**
* Function to generate a slug (a normalized URL sanitized string)
*
* Turns 'Any impressive headline' to 'any-impressive-headline'
*
* @param string $str String to use to generate slug
* @return string Returns slug
* @author internet
* @license public domain
*
*/
function generate_slug($str)
{
setlocale(LC_ALL, 'en_US.UTF8');
$r = '';
$str = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
for ($i = 0; $i < strlen($str); $i++) {
$ch1 = $str[$i];
$ch2 = mb_substr($str, $i, 1);
$r .= $ch1 == '?' ? $ch2 : $ch1;
}
$str = str_replace(
array('&auml;', '&ouml;', '&uuml;', '&szlg', '&amp;', ' & ', '&', ' - ', '/', ' / ', ' ', '='),
array('ae', 'oe', 'ue', 'ss', '-and-', '-and-', '-and-', '-', '-', '-', '-', '-'),
strtolower($r)
);
$chars = "abcdefghijklmnopqrstuvwxyz0123456789_-";
$replace = '';
for ($i=0; $i<strlen($str); $i++) {
if (false !== strpos($chars, $str[$i])) {
$replace .= $str[$i];
}
}
return $replace;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment