Last active
August 17, 2021 05:30
-
-
Save devsrealm/0dfbad79008733e367f47a8a86b84b1f to your computer and use it in GitHub Desktop.
Super Simple Seo Friendly Slug In PHP
This file contains 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 | |
/** | |
* @param $string | |
* @param string $separator | |
* @return string | |
* @author DevsrealmGuy | |
*/ | |
public function slug($string, string $separator = '-'): string | |
{ | |
# | |
# Replace chars and trim before it gets to Transliterator | |
# | |
$string = trim( | |
str_replace( | |
search: ['&', '@', '%', '$', '*', '<', '>', '+', '-'], | |
replace: [' and ', ' at ', ' percentage ', ' dollar ', | |
' asterisk ', ' less than ', ' greater than ', ' plus ', ' minus '], | |
subject: $string) | |
); | |
# | |
# You can use simple regex like so: '::[^A-Za-z0-9_] Remove;' would remove any character that isn't alphanumeric and underscore | |
# | |
# I have no idea why complex regex ain't working though :( | |
# | |
$rules = '::Lower(); ::[:Punctuation:] Remove; ::Any-Latin; ::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;'; | |
$slug = \Transliterator::createFromRules(rules: $rules); | |
# replace whitespaces or space with separator | |
return preg_replace( | |
pattern: '/[^\S]+/', | |
replacement: $separator, | |
subject: $slug->transliterate($string)); | |
} | |
/** | |
* TEST SLUG: | |
* | |
* $this->slug('Hey ThiS IS Cool & YOU KNOW IT ', '-') | |
* "hey-this-is-cool-and-you-know-it" | |
* | |
* $this->slug('PLAYING WITH SYMBOLS: $,&,*,<,>,+,@,-,%', '-') | |
* "playing-with-symbols-dollar-and-asterisk-less-than-greater-than-plus-at-minus-percentage" | |
* | |
* $this->slug('嘿,伙计,你过得好吗', '-') | |
* "hei-huo-ji-ni-guo-de-hao-ma" | |
* | |
* $this->slug('調子はどうだい、元気だといいな', '-'), | |
* "diao-zihadoudai-yuan-qidatoiina" | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment