Converts a string into a slug.
Developed by Florian Eckerstorfer in Vienna, Europe with the help of many 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 and Vietnamese special
characters. Instead of removing these characters, Slugify approximates them (e.g.,
ae
replacesä
). - No external dependencies.
- PSR-4 compatible.
- Compatible with PHP >= 5.5.9 and PHP 7.
- Integrations for Symfony (2 and 3), Silex (1 and 2), Laravel, Twig (1 and 2), Zend Framework 2, Nette Framework, Latte and Plum.
You can install Slugify through Composer:
$ 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 the PHP documentation.
Further steps may be needed for integrations.
Generate a slug:
use Cocur\Slugify\Slugify;
$slugify = new Slugify();
echo $slugify->slugify('Hello World!'); // hello-world
You can also change the separator used by Slugify
:
echo $slugify->slugify('Hello World!', '_'); // hello_world
The library also contains Cocur\Slugify\SlugifyInterface
. Use this interface whenever you need to type hint an
instance of Slugify
.
To add additional transliteration rules you can use the addRule()
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 categorized
using rulesets. Rules for the most popular are activated by default in a specific order. You can change which rulesets
are activated and the order in which they are activated. The order is important when there are conflicting rules in
different languages. For example, in German ä
is transliterated with ae
, in Turkish the correct transliteration is
a
. By default the German transliteration is used since German is used more often on the internet. If you want to use
prefer the Turkish transliteration you have to possibilities. You can activate it after creating the constructor:
$slugify = new Slugify();
$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 = new Slugify(['rulesets' => ['default', 'turkish']]);
$slugify->slugify('ä'); // -> "a"
You can find a list of the available rulesets in Resources/rules.
The constructor takes an options array, you have already seen the rulesets
options above. You can also change the
regular expression that is used to replace characters with the separator.
$slugify = new Slugify(['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 the
lowercase
option to false.
$slugify = new Slugify(['lowercase' => false]);
$slugify->slugify('Hello World'); // -> "Hello-World"
By default Slugify will use dashes as separators. If you want to use a different default separator, you can set the
separator
option.
$slugify = new Slugify(['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 to
be trimmed you can set the trim
option to false.
$slugify = new Slugify(['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 the slugify()
method. For example:
$slugify = new Slugify();
$slugify->slugify('Hello World', ['lowercase' => false]); // -> "Hello-World"
You can also modify the separator this way:
$slugify = new Slugify();
$slugify->slugify('Hello World', ['separator' => '_']); // -> "hello_world"
You can even activate a custom ruleset without touching the default rules:
$slugify = new Slugify();
$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 of the language and question. Feel free to ask for additional languages in the issues, but please note that the maintainer of this repository does not speak all languages. If you can provide a Pull Request with rules for a 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 your test 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 found here.
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 in the Cocur\Slugify\Bridge\Symfony
namespace and you only need to add the bundle class
to your AppKernel.php
:
# app/AppKernel.php
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
// ...
new Cocur\Slugify\Bridge\Symfony\CocurSlugifyBundle(),
);
// ...
}
// ...
}
You can now use the cocur_slugify
service everywhere in your application, for example, in your controller:
$slug = $this->get('cocur_slugify')->slugify('Hello World!');
The bundle also provides an alias slugify
for the cocur_slugify
service:
$slug = $this->get('slugify')->slugify('Hello World!');
If you use autowire
(Symfony >=3.3), you can inject it into your services like this:
public function __construct(\Cocur\Slugify\SlugifyInterface $slugify)
You can set the following configuration settings in config.yml
to adjust the slugify service:
cocur_slugify:
lowercase: <boolean>
separator: <string>
regexp: <string>
rulesets: { } # 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 filter slugify
in your templates after you have setup
Symfony 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:
use Cocur\Slugify\Bridge\Twig\SlugifyExtension;
use Cocur\Slugify\Slugify;
$twig = new Twig_Environment($loader);
$twig->addExtension(new SlugifyExtension(Slugify::create()));
To use the Twig filter with TwigBridge for Laravel, you'll need to add the Slugify extension using a closure:
// laravel/app/config/packages/rcrowe/twigbridge/config.php
'extensions' => array(
//...
function () {
return new \Cocur\Slugify\Bridge\Twig\SlugifyExtension(\Cocur\Slugify\Slugify::create());
},
),
You can find more information about registering extensions in the Twig documentation.
Slugify also provides a service provider to integrate into Silex.
// For Silex version 1
$app->register(new Cocur\Slugify\Bridge\Silex\SlugifyServiceProvider());
// For Silex version 2
$app->register(new Cocur\Slugify\Bridge\Silex2\SlugifyServiceProvider());
You can use the slugify
method in your controllers:
$app->get('/', function () {
return $app['slugify']->slugify('welcome to the homepage');
});
And if you use Silex in combination with Twig register the SlugifyServiceProvider
after the Silex\Provider\TwigServiceProvider
to add the Twig extension to your environment and use the slugify
filter in your templates.
{{ 'welcome to the homepage'|slugify }}
We don't need an additional integration to use Slugify in Mustache.php. If you want to use Slugify in Mustache, just add a helper:
use Cocur\Slugify\Slugify;
$mustache = new Mustache_Engine(array(
// ...
'helpers' => array('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's app/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 the Slugify::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 helper already registered for you.
Just enable the module in your configuration like this.
return array(
//...
'modules' => array(
'Application',
'ZfcBase',
'Cocur\Slugify\Bridge\ZF2' // <- Add this line
//...
)
//...
);
After that you can retrieve the Cocur\Slugify\Slugify
service (or the slugify
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 the slugify
helper to generate slugs.
<?php echo $this->slugify('Hällo Wörld') ?>
<?php echo $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 array(
'cocur_slugify' => array(
'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 to
register it in your config.neon
:
# app/config/config.neon
extensions:
slugify: Cocur\Slugify\Bridge\Nette\SlugifyExtension
You can now use the Cocur\Slugify\SlugifyInterface
service everywhere in your application, for example in your
presenter:
class MyPresenter extends \Nette\Application\UI\Presenter
{
/** @var \Cocur\Slugify\SlugifyInterface @inject */
public $slugify;
public function renderDefault()
{
$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 filter slugify
in your
templates 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:
use Cocur\Slugify\Bridge\Latte\SlugifyHelper;
use Cocur\Slugify\Slugify;
use Latte;
$latte = new Latte\Engine();
$latte->addFilter('slugify', array(new SlugifyHelper(Slugify::create()), 'slugify'));
Slugify does not need a specific bridge to work with Slim 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(new Slim\Views\TwigExtension($c->get('router'), $c->get('request')->getUri()));
$view->addExtension(new Cocur\Slugify\Bridge\Twig\SlugifyExtension(Cocur\Slugify\Slugify::create()));
return $view;
};
In a template you can use it like this:
<a href="/blog/{{ post.title|slugify }}">{{ post.title|raw }}</a></h5>
Slugify provides a service provider for use with league/container
:
use Cocur\Slugify;
use League\Container;
/* @var Container\ContainerInterface $container */
$container->addServiceProvider(new Slugify\Bridge\League\SlugifyServiceProvider());
/* @var Slugify\Slugify $slugify */
$slugify = $container->get(Slugify\SlugifyInterface::class);
You can configure it by sharing the required options:
use Cocur\Slugify;
use League\Container;
/* @var Container\ContainerInterface $container */
$container->share('config.slugify.options', [
'lowercase' => false,
'rulesets' => [
'default',
'german',
],
]);
$container->addServiceProvider(new Slugify\Bridge\League\SlugifyServiceProvider());
/* @var Slugify\Slugify $slugify */
$slugify = $container->get(Slugify\SlugifyInterface::class);
You can configure which rule provider to use by sharing it:
use Cocur\Slugify;
use League\Container;
/* @var Container\ContainerInterface $container */
$container->share(Slugify\RuleProvider\RuleProviderInterface::class, function () {
return new Slugify\RuleProvider\FileRuleProvider(__DIR__ . '/../../rules');
]);
$container->addServiceProvider(new Slugify\Bridge\League\SlugifyServiceProvider());
/* @var Slugify\Slugify $slugify */
$slugify = $container->get(Slugify\SlugifyInterface::class);
- #183 Fix invalid JSON (RusiPapazov)
- #185 Fix support for Symfony > 3.3 (by FabienPapet)
- #186 Require Multibyte extension in
composer.json
(by wandersonwhcr)
- HHVM is no longer supported
- Bugfix #165 Added missing French rules to
DefaultRuleProvider
(by gsouf) - #168 Add Persian rules (by mohammad6006)
- Bugfix #169 Add missing
getName()
toCocur\Slugify\Bridge\Twig\SlugifyExtension
(by TomCan) - #172 Sort rules in
DefaultRuleProvider
alphabetically (by tbmatuka) - #174 Add Hungarian rules (by rviktor87)
- #180 Add Brazilian Portuguese rules (by tallesairan)
- Bugfix #181 Add missing French rules (by FabienPapet)
- #150 Add Romanian rules (by gabiudrescu)
- #154 Add French rules (by SuN-80)
- #159 Add Estonian rules (by erkimiilberg)
- #162 Add support for Twig 2 (by JakeFr)
- #133 Allow to modify options without creating a new object (by leofeyer)
- #135 Add support for Danish (by izehose)
- #140 Update Hindi support (by arunlodhi)
- #146 Add support for Italien (by gianiaz)
- #151 Add support for Serbian (by cvetan)
- #155 Update support for Lithuanian (by s4uliu5)
- #124 Fix support for Bulgarian
- #125 Update Silex 2 provider (by JakeFr)
- #129 Add support for Croatian (by napravicukod)
- #102 Add transliterations for Azerbaijani (by seferov)
- #109 Made integer values into strings (by JonathanMH)
- #114 Provide SlugifyServiceProvider for league/container (by localheinz)
- #120 Add compatibility with Silex 2 (by shamotj)
- Do not activate Swedish rules by default (fixes broken v2.1 release)
- #78 Use multibyte-safe case convention (by Koc)
- #81 Move rules into JSON files (by florianeckerstorfer)
- #84 Add tests for very long strings containing umlauts (by florianeckerstorfer)
- #88 Add rules for Hindi (by florianeckerstorfer)
- #89 Add rules for Norwegian (by tsmes)
- #90 Replace
bindShared
withsingleton
in Laravel bridge (by sunspikes) - #97 Set minimum PHP version to 5.5.9 (by florianeckerstorfer)
- #98 Add rules for Bulgarian (by RoumenDamianoff)
- #75 Remove a duplicate array entry (by irfanevrens)
- #76 Add support for Georgian (by TheGIBSON)
- #77 Fix Danish transliterations (by kafoso)
- #70 Add missing superscript and subscript digits (by BlueM)
- #71 Improve Greek language support (by kostaspt)
- #72 Improve Silex integration (by CarsonF)
- #73 Improve Russian language support (by akost)
- Add integration for Plum (by florianeckerstorfer)
- #64 Fix Nette integration (by lookyman)
- Add option to not convert slug to lowercase (by florianeckerstorfer and GDmac)
- #54 Add support for Burmese characters (by lovetostrike)
- #58 Add Nette and Latte integration (by lookyman)
- #50 Fix transliteration for Vietnamese character Đ (by mac2000)
No new features or bugfixes, but it's about time to pump Slugify to v1.0.
- #44 Change visibility of properties to
protected
(by acelaya) - #45 Configure regular expression used to replace characters (by acelaya)
- Fix type hinting (by florianeckerstorfer)
- Remove duplicate rule (by florianeckerstorfer)
- #39 Add support for rulesets (by florianeckerstorfer)
- #32 Added Laraval bridge (by cviebrock)
- #35 Fixed transliteration for
Ď
(by michalskop)
- #28 Add Symfony2 service alias and make Twig extension private (by Kevin Bond)
- #27 Add support for Arabic characters (by Davide 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 (by Michel Petit)
- #21 Added support for Greek characters (by Michel Petit)
- #20 Fixed rule for cyrillic letter D (by Marchenko Alexandr)
- Add missing
$separator
parameter toSlugifyInterface
- #19 Adds soft sign rule (by Marchenko Alexandr)
Nearly completely rewritten code, removes iconv
support because the underlying library is broken. The code is now better and faster. Many thanks to Marchenko Alexandr.
- #11 PSR-4 compatible (by mac2000)
- #13 Added editorconfig (by mac2000)
- #14 Return empty slug when input is empty and removed unused parameter (by mac2000)
Support for Chinese is adapted from jifei/Pinyin with permission.
Slugify is a project of Cocur. You can contact us on Twitter: @cocurco
If you need support you can ask on Twitter (well, only if your question is short) or you can join our chat on Gitter.
In case you want to support the development of Slugify you can help us with providing additional transliterations or inform us if a transliteration is wrong. We would highly appreciate it if you can send us directly a Pull Request on Github. If you have never contributed to a project on Github we are happy to help you. Just ask on Twitter or directly join our Gitter.
You always can help me (Florian, the original developer and maintainer) out by sending 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 associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons 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 the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.