Skip to content

Instantly share code, notes, and snippets.

@jonbrockett
Created January 17, 2019 14:28
Show Gist options
  • Select an option

  • Save jonbrockett/fe5d8d311f7294919968e3445a44c63d to your computer and use it in GitHub Desktop.

Select an option

Save jonbrockett/fe5d8d311f7294919968e3445a44c63d to your computer and use it in GitHub Desktop.
String to Slug
/** Convert string to slug */
require_once( 'library/string-to-slug.php' );
<?php
/**
* Return the slug of a string to be used in a URL.
*
* @return String
*/
function to_slug($text){
// replace non letter or digits by -
$text = preg_replace('~[^\pL\d]+~u', '-', $text);
// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
// trim
$text = trim($text, '-');
// remove duplicated - symbols
$text = preg_replace('~-+~', '-', $text);
// lowercase
$text = strtolower($text);
if (empty($text)) {
return 'n-a';
}
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment