Last active
August 29, 2015 13:58
-
-
Save kohnmd/9956307 to your computer and use it in GitHub Desktop.
Converts a string into a slug. JS and PHP versions.
This file contains hidden or 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
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, ""); | |
} |
This file contains hidden or 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 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