Created
March 14, 2019 03:54
-
-
Save pixelsoul/bc3bdc67058b2d6c7b935bd5b1cd0cf9 to your computer and use it in GitHub Desktop.
slugify a 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
<?php | |
function slugify($string){ | |
// trim off hyphens on ends of string | |
$string = trim($string, '-'); | |
// replace all non-standard characters or numbers | |
$string = preg_replace('~[^\\pL\d]+~u', '-', $string); | |
// transliterate | |
if(function_exists('transliterator_transliterate')){ | |
$string = transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()', $string); | |
} | |
elseif(function_exists('iconv')){ | |
$string = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $string); | |
} | |
// convert string to lowercase | |
$string = strtolower($string); | |
// remove unwanted characters | |
$string = preg_replace('~[^-\w]+~', '', $string); | |
// check if string is empty | |
if (empty($string)){ | |
return 'n-a'; | |
} | |
return $string; | |
} | |
$string = "this ^string (contains) #special cha-racters! ümlaut 1234-"; | |
print(slugify($string)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment