Skip to content

Instantly share code, notes, and snippets.

@tlongren
Last active December 23, 2020 13:32
Show Gist options
  • Save tlongren/5527129 to your computer and use it in GitHub Desktop.
Save tlongren/5527129 to your computer and use it in GitHub Desktop.
PHP Clean URL (SLUG) Generator
<?php
$slug = slugit("thank you for visiting");
echo $slug;
// returns: thank-you-for-visiting
?>
<?php
setlocale(LC_ALL, 'en_US.UTF8');
function slugit($str, $replace=array(), $delimiter='-') {
if ( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
return $clean;
}
?>
@Samirdatainflow
Copy link

If you are working with PHP- Codeigniter framework and you want to Generate URL slug in Codeigniter then follow this link
https://datainflow.com/generate-url-slug-codeigniter/

@wnedoe
Copy link

wnedoe commented Dec 23, 2020

Be aware that setlocale(LC_ALL, 'en_US.UTF8'); will influence the output!

e.g. if ö will be converted to o or oe (latter e.g. for german)

So dependent on you target audience you should use their locale for this function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment