Skip to content

Instantly share code, notes, and snippets.

@Sigmus
Created July 10, 2014 14:23
Show Gist options
  • Save Sigmus/5dbd53237ed523b85f80 to your computer and use it in GitHub Desktop.
Save Sigmus/5dbd53237ed523b85f80 to your computer and use it in GitHub Desktop.
PHP slug function
<?php
// Extracted from the Laravel Framework (http://laravel.com)
function toSlug($title, $separator = '-', $to_lower = true) {
// Convert all dashes/underscores into separator
$flip = $separator == '-' ? '_' : '-';
$title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);
if ($to_lower) {
$title = mb_strtolower($title);
}
// Remove all characters that are not the separator, letters, numbers, or whitespace.
$title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', $title);
// Replace all separator characters and whitespace by a single separator
$title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);
return trim($title, $separator);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment