Last active
September 22, 2019 17:58
-
-
Save igor822/8795879 to your computer and use it in GitHub Desktop.
String to Slug
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
String.prototype.toSlug = function(){ | |
str = this.replace(/^\s+|\s+$/g, ''); // trim | |
str = str.toLowerCase(); | |
// remove accents, swap ñ for n, etc | |
var from = "ãàáäâèéëêìíïîõòóöôùúüûñç·/_,:;"; | |
var to = "aaaaaeeeeiiiiooooouuuunc------"; | |
for (var i=0, l=from.length ; i<l ; i++) { | |
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)); | |
} | |
str = str.replace(/[^a-z0-9 -]/g, '').replace(/\s+/g, '-').replace(/-+/g, '-'); | |
return str; | |
}; |
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 toSlug($str) { | |
$str = strtolower(utf8_decode($str)); $i=1; | |
$str = strtr($str, utf8_decode('àáâãäåæçèéêëìíîïñòóôõöøùúûüýýÿ'), 'aaaaaaaceeeeiiiinoooooouuuuyyy'); | |
$str = preg_replace("/([^a-z0-9])/",'-',utf8_encode($str)); | |
while($i>0) $str = str_replace('--','-',$str,$i); | |
if (substr($str, -1) == '-') $str = substr($str, 0, -1); | |
return $str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment