Skip to content

Instantly share code, notes, and snippets.

@vincentorback
Last active October 28, 2017 03:28
Show Gist options
  • Save vincentorback/53c83177302b3888d5ff3404f3a94db4 to your computer and use it in GitHub Desktop.
Save vincentorback/53c83177302b3888d5ff3404f3a94db4 to your computer and use it in GitHub Desktop.
Slugify a string - javascript and php
/**
* 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
}
<?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