- Notifications
You must be signed in to change notification settings - Fork249
Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.
License
cocur/slugify
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Converts a string into a slug.
Developed byFlorian Eckerstorfer in Vienna, Europe with the help ofmany great contributors.
- Removes all special characters from a string.
- Provides custom replacements for Arabic, Austrian, Azerbaijani, Brazilian Portuguese, Bulgarian, Burmese, Chinese, Croatian, Czech, Esperanto, Estonian, Finnish, French, Georgian, German, Greek, Hindi, Hungarian, Italian, Latvian, Lithuanian, Macedonian, Norwegian, Polish, Romanian, Russian, Serbian, Spanish, Swedish, Turkish, Ukrainian, Vietnamese and Yiddish special characters. Instead of removing these characters, Slugify approximates them (e.g.,
ae
replacesä
). - No external dependencies.
- PSR-4 compatible.
- Compatible with PHP >= 8.
- Integrations forSymfony (3, 4 and 5),Laravel,Twig (2 and 3),Zend Framework 2,Nette Framework,Latte andPlum.
You can install Slugify throughComposer:
composer require cocur/slugify
Slugify requires the Multibyte String extension from PHP. Typically you can use the configure option--enable-mbstring
while compiling PHP. More information can be found in thePHP documentation.
Further steps may be needed forintegrations.
Generate a slug:
useCocur\Slugify\Slugify;$slugify =newSlugify();echo$slugify->slugify("Hello World!");// hello-world
You can also change the separator used bySlugify
:
echo$slugify->slugify("Hello World!","_");// hello_world
The library also containsCocur\Slugify\SlugifyInterface
. Use this interface whenever you need to type hint aninstance ofSlugify
.
To add additional transliteration rules you can use theaddRule()
method.
$slugify->addRule("i","ey");echo$slugify->slugify("Hi");// hey
Many of the transliterations rules used in Slugify are specific to a language. These rules are therefore categorizedusing rulesets. Rules for the most popular are activated by default in a specific order. You can change which rulesetsare activated and the order in which they are activated. The order is important when there are conflicting rules indifferent languages. For example, in Germanä
is transliterated withae
, in Turkish the correct transliteration isa
. By default the German transliteration is used since German is used more often on the internet. If you want to useprefer the Turkish transliteration you have to possibilities. You can activate it after creating the constructor:
$slugify =newSlugify();$slugify->slugify("ä");// -> "ae"$slugify->activateRuleSet("turkish");$slugify->slugify("ä");// -> "a"
An alternative way would be to pass the rulesets and their order to the constructor.
$slugify =newSlugify(["rulesets" => ["default","turkish"]]);$slugify->slugify("ä");// -> "a"
You can find a list of the available rulesets inResources/rules.
The constructor takes an options array, you have already seen therulesets
options above. You can also change theregular expression that is used to replace characters with the separator.
$slugify =newSlugify(["regexp" =>"/([^A-Za-z0-9]|-)+/"]);
(The regular expression used in the example above is the default one.)
By default Slugify will convert the slug to lowercase. If you want to preserve the case of the string you can set thelowercase
option to false.
$slugify =newSlugify(["lowercase" =>false]);$slugify->slugify("Hello World");// -> "Hello-World"
Lowercasing is done before using the regular expression. If you want to keep the lowercasing behavior but your regularexpression needs to match uppercase letters, you can set thelowercase_after_regexp
option totrue
.
$slugify =newSlugify(["regexp" =>"/(?<=[[:^upper:]])(?=[[:upper:]])/","lowercase_after_regexp" =>false,]);$slugify->slugify("FooBar");// -> "foo-bar"
By default Slugify will use dashes as separators. If you want to use a different default separator, you can set theseparator
option.
$slugify =newSlugify(["separator" =>"_"]);$slugify->slugify("Hello World");// -> "hello_world"
By default Slugify will remove leading and trailing separators before returning the slug. If you do not want the slug tobe trimmed you can set thetrim
option to false.
$slugify =newSlugify(["trim" =>false]);$slugify->slugify("Hello World");// -> "hello-world-"
You can overwrite any of the above options on the fly by passing an options array as second argument to theslugify()
method. For example:
$slugify =newSlugify();$slugify->slugify("Hello World", ["lowercase" =>false]);// -> "Hello-World"
You can also modify the separator this way:
$slugify =newSlugify();$slugify->slugify("Hello World", ["separator" =>"_"]);// -> "hello_world"
You can even activate a custom ruleset without touching the default rules:
$slugify =newSlugify();$slugify->slugify("für", ["ruleset" =>"turkish"]);// -> "fur"$slugify->slugify("für");// -> "fuer"
We really appreciate if you report bugs and errors in the transliteration, especially if you are a native speaker ofthe language and question. Feel free to ask for additional languages in the issues, but please note that themaintainer of this repository does not speak all languages. If you can provide a Pull Request with rules fora new language or extend the rules for an existing language that would be amazing.
To add a new language you need to:
- Create a
[language].json
inResources/rules
- If you believe the language should be a default ruleset you can add the language to
Cocur\Slugify\Slugify::$options
. If you add the language there all existing tests still have to pass - Run
php bin/generate-default.php
- Add tests for the language in
tests/SlugifyTest.php
. If the language is in the default ruleset add yourtest cases todefaultRuleProvider()
, otherwise tocustomRulesProvider()
.
Submit PR. Thank you very much. 💚
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
The full Code of Conduct can be foundhere.
This project is no place for hate. If you have any problems please contact Florian:florian@eckerstorfer.net ✌🏻🏳️🌈
Slugify contains a Symfony bundle and service definition that allow you to use it as a service in your Symfony application. The code resides inCocur\Slugify\Bridge\Symfony\CocurSlugifyBundle
and you only need to activate it:
Support for Symfony 2 has been dropped in Slugify 4.0.0, usecocur/slugify@3
.
// app/AppKernel.phpclass AppKernelextends Kernel{publicfunctionregisterBundles() {$bundles = [// ...newCocur\Slugify\Bridge\Symfony\CocurSlugifyBundle(), ]; }}
// config/bundles.phpreturn [// ...Cocur\Slugify\Bridge\Symfony\CocurSlugifyBundle::class => ["all" =>true],];
You can now use thecocur_slugify
service everywhere in your application, for example, in your controller:
$slug =$this->get("cocur_slugify")->slugify("Hello World!");
The bundle also provides an aliasslugify
for thecocur_slugify
service:
$slug =$this->get("slugify")->slugify("Hello World!");
If you useautowire
(Symfony >=3.3), you can inject it into your services like this:
publicfunction __construct(\Cocur\Slugify\SlugifyInterface$slugify)
You can set the following configuration settings inconfig.yml
(Symfony 2-3) orconfig/packages/cocur_slugify.yaml
(Symfony 4) to adjust the slugify service:
cocur_slugify:lowercase:false# or trueseparator:"-"# any string# regexp: <string>rulesets:["austrian"]# List of rulesets: https://github.com/cocur/slugify/tree/master/Resources/rules
If you use the Symfony framework with Twig you can use the Twig filterslugify
in your templates after you have setupSymfony integrations (see above).
{{'Hällo Wörld'|slugify }}
If you use Twig outside of the Symfony framework you first need to add the extension to your environment:
useCocur\Slugify\Bridge\Twig\SlugifyExtension;useCocur\Slugify\Slugify;$twig =newTwig_Environment($loader);$twig->addExtension(newSlugifyExtension(Slugify::create()));
To use the Twig filter withTwigBridge for Laravel, you'll need to add theSlugify extension using a closure:
// laravel/app/config/packages/rcrowe/twigbridge/config.php'extensions' =>array(//...function () {returnnew \Cocur\Slugify\Bridge\Twig\SlugifyExtension(\Cocur\Slugify\Slugify::create()); },),
You can find more information about registering extensions in theTwig documentation.
We don't need an additional integration to use Slugify inMustache.php.If you want to use Slugify in Mustache, just add a helper:
useCocur\Slugify\Slugify;$mustache =newMustache_Engine([// ..."helpers" => ["slugify" =>function ($string,$separator =null) {return Slugify::create()->slugify($string,$separator); }, ],]);
Slugify also provides a service provider to integrate into Laravel (versions 4.1 and later).
In your Laravel project'sapp/config/app.php
file, add the service provider into the "providers" array:
'providers' =>array("Cocur\Slugify\Bridge\Laravel\SlugifyServiceProvider",)
And add the facade into the "aliases" array:
'aliases' =>array("Slugify" =>"Cocur\Slugify\Bridge\Laravel\SlugifyFacade",)
You can then use theSlugify::slugify()
method in your controllers:
$url = Slugify::slugify("welcome to the homepage");
Slugify can be easely used in Zend Framework 2 applications. Included bridge provides a service and a view helperalready registered for you.
Just enable the module in your configuration like this.
return [//..."modules" => ["Application","ZfcBase","Cocur\Slugify\Bridge\ZF2",// <- Add this line//... ],//...];
After that you can retrieve theCocur\Slugify\Slugify
service (or theslugify
alias) and generate a slug.
/** @var \Zend\ServiceManager\ServiceManager $sm */$slugify =$sm->get("Cocur\Slugify\Slugify");$slug =$slugify->slugify("Hällo Wörld");$anotherSlug =$slugify->slugify("Hällo Wörld","_");
In your view templates use theslugify
helper to generate slugs.
<?phpecho$this->slugify("Hällo Wörld");?><?phpecho$this->slugify("Hällo Wörld","_");?>
The service (which is also used in the view helper) can be customized by defining this configuration key.
return ["cocur_slugify" => ["reg_exp" =>"/([^a-zA-Z0-9]|-)+/", ],];
Slugify contains a Nette extension that allows you to use it as a service in your Nette application. You only need toregister it in yourconfig.neon
:
# app/config/config.neonextensions:slugify:Cocur\Slugify\Bridge\Nette\SlugifyExtension
You can now use theCocur\Slugify\SlugifyInterface
service everywhere in your application, for example in yourpresenter:
class MyPresenterextends \Nette\Application\UI\Presenter{/** @var \Cocur\Slugify\SlugifyInterface @inject */public$slugify;publicfunctionrenderDefault() {$this->template->hello =$this->slugify->slugify("Hällo Wörld"); }}
If you use the Nette Framework with it's native Latte templating engine, you can use the Latte filterslugify
in yourtemplates after you have setup Nette extension (see above).
{$hello|slugify}
If you use Latte outside of the Nette Framework you first need to add the filter to your engine:
useCocur\Slugify\Bridge\Latte\SlugifyHelper;useCocur\Slugify\Slugify;useLatte;$latte =newLatte\Engine();$latte->addFilter("slugify", [newSlugifyHelper(Slugify::create()),"slugify"]);
Slugify does not need a specific bridge to work withSlim 3, just add the following configuration:
$container["view"] =function ($c) {$settings =$c->get("settings");$view =new \Slim\Views\Twig($settings["view"]["template_path"],$settings["view"]["twig"] );$view->addExtension(newSlim\Views\TwigExtension($c->get("router"),$c->get("request")->getUri() ) );$view->addExtension(newCocur\Slugify\Bridge\Twig\SlugifyExtension(Cocur\Slugify\Slugify::create() ) );return$view;};
In a template you can use it like this:
<ahref="/blog/{{post.title|slugify }}">{{post.title|raw }}</a></h5>
Slugify provides a service provider for use withleague/container
:
useCocur\Slugify;useLeague\Container;/* @var Container\ContainerInterface $container */$container->addServiceProvider(newSlugify\Bridge\League\SlugifyServiceProvider());/* @var Slugify\Slugify $slugify */$slugify =$container->get(Slugify\SlugifyInterface::class);
You can configure it by sharing the required options:
useCocur\Slugify;useLeague\Container;/* @var Container\ContainerInterface $container */$container->share("config.slugify.options", ["lowercase" =>false,"rulesets" => ["default","german"],]);$container->addServiceProvider(newSlugify\Bridge\League\SlugifyServiceProvider());/* @var Slugify\Slugify $slugify */$slugify =$container->get(Slugify\SlugifyInterface::class);
You can configure which rule provider to use by sharing it:
useCocur\Slugify;useLeague\Container;/* @var Container\ContainerInterface $container */$container->share(Slugify\RuleProvider\RuleProviderInterface::class,function () {returnnewSlugify\RuleProvider\FileRuleProvider(__DIR__ .'/../../rules');]);$container->addServiceProvider(newSlugify\Bridge\League\SlugifyServiceProvider());/* @var Slugify\Slugify $slugify */$slugify =$container->get(Slugify\SlugifyInterface::class);
- #336 Add Yiddish language ruleset (yankl)
- #340 Fix for Symfony 7.1 (byEvgeny1973)
- #342 Fix PHP 8.4 deprecation about implicit null arguments (byshyim)
- Drop support for PHP 7 and fix version constraints
- Replaces v4.5.0
- #327 Add Korean to default ruleset
- Replaced by v4.5.1 since this release breaks compatibility with PHP 7
- Remove PHP 7 from compatibility list
- Replaces v4.4.0
- #320 Add Korean (byMrMooky)
- #322 Add types to avoid PHP 8.2 deprecation warning (byantoniovj1)
- Replaced by v4.4.1 since this release broke compatibility with PHP 7
- #305 Add support for custom fonts (byluca-alsina)
- #309 Add handling for undefined rulesets (byaadmathijssen)
- #227 Add support for capital sharp s (byweeman1337)
- #312 Fix composer.lock file (byflorianeckerstorfer)
- #313 Update PHP version requirement (byflorianeckerstorfer)
Support for Symfony 6.
- #244 .gitignore cleanup (bykubawerlos)
- #259 Fix portuguese-brazil language (bystephandesouza)
- #272 Improve tests about assertions (bypeter279k)
- #278 Update georgian.json (bynikameto)
- #299 Allow Symfony 6 and resolve depreciations (byGromNaN)
- #264 Add new Gujarati language (byinfynnoTech)
- #297 More Yoruba character support (by9jaGuy)
Version 4 does not introduce new major features, but adds support for Symfony 4 and 5, Twig 3 and, most importantly, PHP 7.3 and 7.4.
Support for PHP 5, Twig 1 and Silex is dropped.
- #230 Add Slovak rules (bybartko-s)
- #236 Make Twig Bridge compatible with Twig 3.0 (bymhujer)
- #237 Fix Travis CI configuration (bykubawerlos)
- #238 Drop Twig 1 support (byFabienPapet)
- #239 Fix AppVeyor (bykubawerlos)
- #241 Update .gitattributes (bykubawerlos)
- #242 Add PHP CS Fixer (bykubawerlos)
- #243 Normalize composer.json (bykubawerlos)
- #246 Add support for PHP 7.3 and 7.4 (bysnapshotpl)
- #247 AppVeyor improvements (bykubawerlos)
- #249 PHPUnit annotations should be a FQCNs including a root namespace (bykubawerlos)
- #250 Add support for Symfony 4 and 5 (byfranmomu)
- #251 Dropping support for PHP 5 (byfranmomu)
- #253 Add conflict for unmaintained Symfony versions (byfranmomu)
- #201 Add strip_tags option (bythewilkybarkid)
- #212 Fix Macedonian Dze (byfranmomu)
- #213 Add support for Turkmen (byumbarov)
- #216 Add lowercase_after_regexp option (byjulienfalque)
- #217 Simplify default regular impression (byjulienfalque)
- #220 Fix deprecation warning for symfony/config 4.2+ (byfranmomu)
- #221 Add suuport Armenian (byboolfalse)
- #183 Fix invalid JSON (RusiPapazov)
- #185 Fix support for Symfony > 3.3 (byFabienPapet)
- #186 Require Multibyte extension in
composer.json
(bywandersonwhcr)
- HHVM is no longer supported
- Bugfix#165 Added missing French rules to
DefaultRuleProvider
(bygsouf) - #168 Add Persian rules (bymohammad6006)
- Bugfix#169 Add missing
getName()
toCocur\Slugify\Bridge\Twig\SlugifyExtension
(byTomCan) - #172 Sort rules in
DefaultRuleProvider
alphabetically (bytbmatuka) - #174 Add Hungarian rules (byrviktor87)
- #180 Add Brazilian Portuguese rules (bytallesairan)
- Bugfix#181 Add missing French rules (byFabienPapet)
- #150 Add Romanian rules (bygabiudrescu)
- #154 Add French rules (bySuN-80)
- #159 Add Estonian rules (byerkimiilberg)
- #162 Add support for Twig 2 (byJakeFr)
- #133 Allow to modify options without creating a new object (byleofeyer)
- #135 Add support for Danish (byizehose)
- #140 Update Hindi support (byarunlodhi)
- #146 Add support for Italien (bygianiaz)
- #151 Add support for Serbian (bycvetan)
- #155 Update support for Lithuanian (bys4uliu5)
- #124 Fix support for Bulgarian
- #125 Update Silex 2 provider (byJakeFr)
- #129 Add support for Croatian (bynapravicukod)
- #102 Add transliterations for Azerbaijani (byseferov)
- #109 Made integer values into strings (byJonathanMH)
- #114 Provide SlugifyServiceProvider for league/container (bylocalheinz)
- #120 Add compatibility with Silex 2 (byshamotj)
- Do not activate Swedish rules by default (fixes broken v2.1 release)
- #78 Use multibyte-safe case convention (byKoc)
- #81 Move rules into JSON files (byflorianeckerstorfer)
- #84 Add tests for very long strings containing umlauts (byflorianeckerstorfer)
- #88 Add rules for Hindi (byflorianeckerstorfer)
- #89 Add rules for Norwegian (bytsmes)
- #90 Replace
bindShared
withsingleton
in Laravel bridge (bysunspikes) - #97 Set minimum PHP version to 5.5.9 (byflorianeckerstorfer)
- #98 Add rules for Bulgarian (byRoumenDamianoff)
- #75 Remove a duplicate array entry (byirfanevrens)
- #76 Add support for Georgian (byTheGIBSON)
- #77 Fix Danish transliterations (bykafoso)
- #70 Add missing superscript and subscript digits (byBlueM)
- #71 Improve Greek language support (bykostaspt)
- #72 Improve Silex integration (byCarsonF)
- #73 Improve Russian language support (byakost)
- Add integration forPlum (byflorianeckerstorfer)
- #64 Fix Nette integration (bylookyman)
- Add option to not convert slug to lowercase (byflorianeckerstorfer andGDmac)
- #54 Add support for Burmese characters (bylovetostrike)
- #58 Add Nette and Latte integration (bylookyman)
- #50 Fix transliteration for Vietnamese character Đ (bymac2000)
No new features or bugfixes, but it's about time to pump Slugify to v1.0.
- #44 Change visibility of properties to
protected
(byacelaya) - #45 Configure regular expression used to replace characters (byacelaya)
- Fix type hinting (byflorianeckerstorfer)
- Remove duplicate rule (byflorianeckerstorfer)
- #39 Add support for rulesets (byflorianeckerstorfer)
- #32 Added Laraval bridge (bycviebrock)
- #35 Fixed transliteration for
Ď
(bymichalskop)
- #28 Add Symfony2 service alias and make Twig extension private (byKevin Bond)
- #27 Add support for Arabic characters (byDavide Bellini)
- Added some missing characters
- Improved organisation of characters in
Slugify
class
This version introduces optional integrations into Symfony2, Silex and Twig. You can still use the library in any other framework. I decided to include these bridges because there exist integrations from other developers, but they use outdated versions of cocur/slugify. Including these small bridge classes in the library makes maintaining them a lot easier for me.
- #22 Added support for Esperanto characters (byMichel Petit)
- #21 Added support for Greek characters (byMichel Petit)
- #20 Fixed rule for cyrillic letter D (byMarchenko Alexandr)
- Add missing
$separator
parameter toSlugifyInterface
- #19 Adds soft sign rule (byMarchenko Alexandr)
Nearly completely rewritten code, removesiconv
support because the underlying library is broken. The code is now better and faster. Many thanks toMarchenko Alexandr.
- #11 PSR-4 compatible (bymac2000)
- #13 Added editorconfig (bymac2000)
- #14 Return empty slug when input is empty and removed unused parameter (bymac2000)
Support for Chinese is adapted fromjifei/Pinyin with permission.
Slugify is a project ofCocur. You can contact us on Twitter:@cocurco
If you need support you can ask onTwitter (well, only if your question is short) or youcan join our chat on Gitter.
In case you want to support the development of Slugify you can help us with providing additional transliterations orinform us if a transliteration is wrong. We would highly appreciate it if you can send us directly a Pull Request onGithub. If you have never contributed to a project on Github we are happy to help you. Just ask on Twitter or directlyjoin our Gitter.
You always can help me (Florian, the original developer and maintainer) out bysending me an Euro or two.
The MIT License (MIT)
Copyright (c) 2012-2017 Florian Eckerstorfer
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associateddocumentation files (the "Software"), to deal in the Software without restriction, including without limitation therights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permitpersons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THEWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS ORCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OROTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
About
Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.