Skip to content

Instantly share code, notes, and snippets.

@zakdances
Created September 2, 2017 01: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 zakdances/06a7cd8dfbcaf06a685e76eab3bb1764 to your computer and use it in GitHub Desktop.
Save zakdances/06a7cd8dfbcaf06a685e76eab3bb1764 to your computer and use it in GitHub Desktop.
<?php
class SlugService
{
public function slugify($string)
{
$sep = '-';
// Replace special chars with hyphen
$arr = array_map(function ($val) {
return preg_replace('/[^a-zA-Z0-9.]+/','-',$val);
}, str_split($string));
// Remove first char hyphen
$arr = array_filter($arr, function ($val, $i) use ($sep, $arr) {
return !($val == $sep && $i == 0);
}, ARRAY_FILTER_USE_BOTH);
// Remove last char hyphen
$arr = array_filter($arr, function ($val, $i) use ($sep, $arr) {
return !($val == $sep && $i == count($arr) - 1);
}, ARRAY_FILTER_USE_BOTH);
// Remove duplicate hyphen
$arr = array_filter($arr, function ($val, $i) use ($sep, $arr) {
$lastVal = $i != 0 ? $arr[$i - 1] : null;
return !($val == $sep && $val == $lastVal);
}, ARRAY_FILTER_USE_BOTH);
return strtolower(implode('', $arr));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment