Last active
May 7, 2021 18:48
-
-
Save attitude/9842170 to your computer and use it in GitHub Desktop.
Function to generate a slug (a normalized URL sanitized string)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "attitude/generate_slug", | |
"autoload": { | |
"files": ["function-generate_slug.php"] | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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('ä', 'ö', 'ü', '&szlg', '&', ' & ', '&', ' - ', '/', ' / ', ' ', '='), | |
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