-
-
Save mi-ca/fb0cb35e3af2efa45163bf2a117905d0 to your computer and use it in GitHub Desktop.
Slugify a string - javascript and php
This file contains 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
/** | |
* Slugify a string | |
* @param {String} text | |
* @return {String} | |
*/ | |
export function slugify(text) { | |
return text.toString().toLowerCase() | |
.replace(/([å,ä])/g, 'a') // Replace å and ä with aa | |
.replace(/(ö)/g, 'o') // Replace ö with o | |
.replace(/\s+/g, '-') // Replace spaces with - | |
.replace(/[^\w\-]+/g, '') // Remove all non-word chars | |
.replace(/\-\-+/g, '-') // Replace multiple - with single - | |
.replace(/^-+/, '') // Trim - from start of text | |
.replace(/-+$/, ''); // Trim - from end of text | |
} |
This file contains 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 | |
/** | |
* Slugify a string | |
* @param [type] $text | |
* @return [type] | |
*/ | |
function slugify ($text) { | |
// replace å, ä with a | |
$text = str_replace(array('å', 'ä'), 'a', $text); | |
// replace ö with o | |
$text = str_replace('ö', 'o', $text); | |
// replace non letter or digits by - | |
$text = preg_replace('~[^\\pL\d]+~u', '-', $text); | |
// trim | |
$text = trim($text, '-'); | |
// transliterate | |
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); | |
// lowercase | |
$text = strtolower($text); | |
// remove unwanted characters | |
$text = preg_replace('~[^-\w]+~', '', $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