Skip to content

Instantly share code, notes, and snippets.

@niketpathak
Last active July 15, 2019 13:38
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 niketpathak/b8ff8db8b3362344cd96369bf2a6a966 to your computer and use it in GitHub Desktop.
Save niketpathak/b8ff8db8b3362344cd96369bf2a6a966 to your computer and use it in GitHub Desktop.
Generate Slug PHP (Safe/clean urls) Original resource: https://stackoverflow.com/a/2955878/4717533
<?php
echo slugify('Hello World///&?Welcome'); // hello-world-welcome
/**
* Generates a slug from the given string
* @param $input The input string
* @param string $replacement The character/string to use as the replacement value
* @return mixed|string
*/
function slugify($input, $replacement = '-') {
if (empty($input)) return '';
// replace non letter or digits
$input = preg_replace('~[^\pL\d]+~u', $replacement, $input); // tilde is only used as a delimiter instead of '/'
// transliterate
$input = iconv('utf-8', 'us-ascii//TRANSLIT', $input);
// remove unwanted characters
$input = preg_replace('~[^'.$replacement.'\w]+~', '', $input);
// trim
$input = trim($input, $replacement);
// remove duplicate/multiple consecutive $replacement instances
$input = preg_replace('~'.$replacement.'+'.'~', $replacement, $input);
// lowercase
return strtolower($input);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment