Last active
July 15, 2019 13:38
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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