Skip to content

Instantly share code, notes, and snippets.

@andyexeter
Created April 17, 2018 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyexeter/61599e07413ee3159592c92849790d29 to your computer and use it in GitHub Desktop.
Save andyexeter/61599e07413ee3159592c92849790d29 to your computer and use it in GitHub Desktop.
Converts a string into a slug
<?php
/**
* Returns a slugified version of a string
*
* E.g: Hello World becomes hello-world
*
* @param string $input
*
* @return string
*/
function slugify($input)
{
$input = strip_tags($input);
// Preserve escaped octets.
$input = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $input);
// Remove percent signs that are not part of an octet.
$input = str_replace('%', '', $input);
// Restore octets.
$input = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $input);
$input = strtolower($input);
$input = preg_replace('/&.+?;/', '', $input); // kill entities
$input = str_replace('.', '-', $input);
// Convert nbsp, ndash and mdash to hyphens
$input = str_replace(['%c2%a0', '%e2%80%93', '%e2%80%94'], '-', $input);
// Strip these characters entirely
$input = str_replace([
// iexcl and iquest
'%c2%a1',
'%c2%bf',
// angle quotes
'%c2%ab',
'%c2%bb',
'%e2%80%b9',
'%e2%80%ba',
// curly quotes
'%e2%80%98',
'%e2%80%99',
'%e2%80%9c',
'%e2%80%9d',
'%e2%80%9a',
'%e2%80%9b',
'%e2%80%9e',
'%e2%80%9f',
// copy, reg, deg, hellip and trade
'%c2%a9',
'%c2%ae',
'%c2%b0',
'%e2%80%a6',
'%e2%84%a2',
// acute accents
'%c2%b4',
'%cb%8a',
'%cc%81',
'%cd%81',
// grave accent, macron, caron
'%cc%80',
'%cc%84',
'%cc%8c',
], '', $input);
// Convert times to x
$input = str_replace('%c3%97', 'x', $input);
$input = preg_replace('/[^%a-z0-9 _-]/', '', $input);
$input = preg_replace('/\s+/', '_', $input);
$input = preg_replace('|_+|', '_', $input);
$input = trim($input, '_');
return $input;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment