Skip to content

Instantly share code, notes, and snippets.

@kdes70
Forked from james2doyle/slugify.php
Created February 28, 2018 08:39
Show Gist options
  • Save kdes70/2c5f6ecdc2a620814cfe68986577358f to your computer and use it in GitHub Desktop.
Save kdes70/2c5f6ecdc2a620814cfe68986577358f to your computer and use it in GitHub Desktop.
Simple slugify function for PHP. Creates a slug for the passed string, taking into account international characters as well.
<?php
function slugify($string, $replace = array(), $delimiter = '-') {
// https://github.com/phalcon/incubator/blob/master/Library/Phalcon/Utils/Slug.php
if (!extension_loaded('iconv')) {
throw new Exception('iconv module not loaded');
}
// Save the old locale and set the new locale to UTF-8
$oldLocale = setlocale(LC_ALL, '0');
setlocale(LC_ALL, 'en_US.UTF-8');
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
if (!empty($replace)) {
$clean = str_replace((array) $replace, ' ', $clean);
}
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower($clean);
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
$clean = trim($clean, $delimiter);
// Revert back to the old locale
setlocale(LC_ALL, $oldLocale);
return $clean;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment