Skip to content

Instantly share code, notes, and snippets.

@pixelsoul
Created March 14, 2019 03:54
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 pixelsoul/bc3bdc67058b2d6c7b935bd5b1cd0cf9 to your computer and use it in GitHub Desktop.
Save pixelsoul/bc3bdc67058b2d6c7b935bd5b1cd0cf9 to your computer and use it in GitHub Desktop.
slugify a string
<?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