Created
September 2, 2017 01:12
-
-
Save zakdances/06a7cd8dfbcaf06a685e76eab3bb1764 to your computer and use it in GitHub Desktop.
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 | |
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