Skip to content

Instantly share code, notes, and snippets.

@kohnmd
Last active August 29, 2015 13:58
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 kohnmd/9956307 to your computer and use it in GitHub Desktop.
Save kohnmd/9956307 to your computer and use it in GitHub Desktop.
Converts a string into a slug. JS and PHP versions.
function str_to_slug(str, sep) {
if (typeof sep == 'undefined') {
sep = '-';
}
// remove extra spaces and convert to lowercase
str = str.toString().trim().toLowerCase();
// convert any character that's not alphanumeric into a separator
str = str.replace(/[^a-z0-9]/g, sep)
// replace any successive separators with a single one
var duplicate_seps_regex = new RegExp(sep+'+', 'g');
str = str.replace(duplicate_seps_regex, sep);
// remove any hanging separators at the end of the string and return
var rtrim_regex = new RegExp(sep+'*$', 'g');
return str.replace(rtrim_regex, "");
}
<?php
function str_to_slug( $str, $sep='-' ) {
// remove extra spaces and convert to lowercase
$str = strtolower(trim($str));
// convert any character that's not alphanumeric into a separator
$str = preg_replace('/[^a-z0-9]/', $sep, $str);
// replace any successive separators with a single one
$str = preg_replace('/'.$sep.'+/', $sep, $str);
// remove any hanging separators at the end of the string and return
return rtrim($str, $sep);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment