2017 © Pedro PelĂĄez
 

library slugify

Converts a string into a slug.

image

cocur/slugify

Converts a string into a slug.

  • Wednesday, March 21, 2018
  • by florianeckerstorfer
  • Repository
  • 45 Watchers
  • 1571 Stars
  • 8,751,863 Installations
  • PHP
  • 227 Dependents
  • 10 Suggesters
  • 167 Forks
  • 16 Open issues
  • 53 Versions
  • 8 % Grown

The README.md

cocur/slugify

Converts a string into a slug., (*1)

Build Status Windows Build status Scrutinizer Quality Score Code Coverage, (*2)

Latest Release MIT License Total Downloads, (*3)

Developed by Florian Eckerstorfer in Vienna, Europe with the help of many great contributors., (*4)

Features

  • 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 >= 7.
  • Integrations for Symfony (3, 4 and 5), Laravel, Twig (2 and 3), Zend Framework 2, Nette Framework, Latte and Plum.

Installation

You can install Slugify through Composer:, (*5)

$ 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., (*6)

Further steps may be needed for integrations., (*7)

Usage

Generate a slug:, (*8)

use Cocur\Slugify\Slugify;

$slugify = new Slugify();
echo $slugify->slugify('Hello World!'); // hello-world

You can also change the separator used by Slugify:, (*9)

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., (*10)

To add additional transliteration rules you can use the addRule() method., (*11)

$slugify->addRule('i', 'ey');
echo $slugify->slugify('Hi'); // hey

Rulesets

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:, (*12)

$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., (*13)

$slugify = new Slugify(['rulesets' => ['default', 'turkish']]);
$slugify->slugify('Ă€'); // -> "a"

You can find a list of the available rulesets in Resources/rules., (*14)

More options

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., (*15)

$slugify = new Slugify(['regexp' => '/([^A-Za-z0-9]|-)+/']);

(The regular expression used in the example above is the default one.), (*16)

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., (*17)

$slugify = new Slugify(['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 regular expression needs to match uppercase letters, you can set the lowercase_after_regexp option to true., (*18)

$slugify = new Slugify([
    '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 the separator option., (*19)

$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., (*20)

$slugify = new Slugify(['trim' => false]);
$slugify->slugify('Hello World '); // -> "hello-world-"

Changing options on the fly

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:, (*21)

$slugify = new Slugify();
$slugify->slugify('Hello World', ['lowercase' => false]); // -> "Hello-World"

You can also modify the separator this way:, (*22)

$slugify = new Slugify();
$slugify->slugify('Hello World', ['separator' => '_']); // -> "hello_world"

You can even activate a custom ruleset without touching the default rules:, (*23)

$slugify = new Slugify();
$slugify->slugify('fĂŒr', ['ruleset' => 'turkish']); // -> "fur"
$slugify->slugify('fĂŒr'); // -> "fuer"

Contributing

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., (*24)

To add a new language you need to:, (*25)

  1. Create a [language].json in Resources/rules
  2. 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
  3. Run php bin/generate-default.php
  4. Add tests for the language in tests/SlugifyTest.php. If the language is in the default ruleset add your test cases to defaultRuleProvider(), otherwise to customRulesProvider().

Submit PR. Thank you very much. 💚, (*26)

Code of Conduct

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., (*27)

The full Code of Conduct can be found here., (*28)

This project is no place for hate. If you have any problems please contact Florian: florian@eckerstorfer.net âœŒđŸ»đŸłïžâ€đŸŒˆ, (*29)

Further information

Integrations

Symfony

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 Cocur\Slugify\Bridge\Symfony\CocurSlugifyBundle and you only need to activate it:, (*30)

Symfony 2

Support for Symfony 2 has been dropped in Slugify 4.0.0, use cocur/slugify@3., (*31)

Symfony 3

// app/AppKernel.php

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...
            new Cocur\Slugify\Bridge\Symfony\CocurSlugifyBundle(),
        );
    }
}

Symfony >= 4

// config/bundles.php

return [
    // ...
    Cocur\Slugify\Bridge\Symfony\CocurSlugifyBundle::class => ['all' => true],
];

You can now use the cocur_slugify service everywhere in your application, for example, in your controller:, (*32)

$slug = $this->get('cocur_slugify')->slugify('Hello World!');

The bundle also provides an alias slugify for the cocur_slugify service:, (*33)

$slug = $this->get('slugify')->slugify('Hello World!');

If you use autowire (Symfony >=3.3), you can inject it into your services like this:, (*34)

public function __construct(\Cocur\Slugify\SlugifyInterface $slugify)

Symfony Configuration

You can set the following configuration settings in config.yml (Symfony 2-3) or config/packages/cocur_slugify.yaml (Symfony 4) to adjust the slugify service:, (*35)

cocur_slugify:
    lowercase: false # or true
    separator: '-' # any string
    # regexp: <string>
    rulesets: ['austrian'] # List of rulesets: https://github.com/cocur/slugify/tree/master/Resources/rules

Twig

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)., (*36)

{{ 'HÀllo Wörld'|slugify }}

If you use Twig outside of the Symfony framework you first need to add the extension to your environment:, (*37)

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:, (*38)

// 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., (*39)

Mustache.php

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:, (*40)

use Cocur\Slugify\Slugify;

$mustache = new Mustache_Engine(array(
    // ...
    'helpers' => array('slugify' => function($string, $separator = null) {
        return Slugify::create()->slugify($string, $separator);
    }),
));

Laravel

Slugify also provides a service provider to integrate into Laravel (versions 4.1 and later)., (*41)

In your Laravel project's app/config/app.php file, add the service provider into the "providers" array:, (*42)

'providers' => array(
    "Cocur\Slugify\Bridge\Laravel\SlugifyServiceProvider",
)

And add the facade into the "aliases" array:, (*43)

'aliases' => array(
    "Slugify" => "Cocur\Slugify\Bridge\Laravel\SlugifyFacade",
)

You can then use the Slugify::slugify() method in your controllers:, (*44)

$url = Slugify::slugify('welcome to the homepage');

Zend Framework 2

Slugify can be easely used in Zend Framework 2 applications. Included bridge provides a service and a view helper already registered for you., (*45)

Just enable the module in your configuration like this., (*46)

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., (*47)

/** @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., (*48)

<?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., (*49)

return array(
    'cocur_slugify' => array(
        'reg_exp' => '/([^a-zA-Z0-9]|-)+/'
    )
);

Nette Framework

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:, (*50)

# 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:, (*51)

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');
    }
}

Latte

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)., (*52)

{$hello|slugify}

If you use Latte outside of the Nette Framework you first need to add the filter to your engine:, (*53)

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'));

Slim 3

Slugify does not need a specific bridge to work with Slim 3, just add the following configuration:, (*54)

$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:, (*55)

<a href="/blog/{{ post.title|slugify }}">{{ post.title|raw }}</a></h5>

League

Slugify provides a service provider for use with league/container:, (*56)

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:, (*57)

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:, (*58)

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);

Change Log

Version 4.0 (14 December 2019)

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., (*59)

Support for PHP 5, Twig 1 and Silex is dropped., (*60)

Version 3.2 (31 January 2019)

Version 3.1 (22 January 2018)

Version 3.0.1 (24 September 2017)

Version 3.0 (11 August 2017)

  • 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() to Cocur\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)

Version 2.5 (23 March 2017)

Version 2.4 (9 February 2017)

Version 2.3 (9 August 2016)

Version 2.2 (10 July 2016)

Version 2.1.1 (8 April 2016)

  • Do not activate Swedish rules by default (fixes broken v2.1 release)

Version 2.1.0 (8 April 2016)

Version 2.0.0 (24 February 2016)

Version 1.4.1 (11 February 2016)

  • #90 Replace bindShared with singleton in Laravel bridge (by sunspikes)

Version 1.4 (29 September 2015)

Version 1.3 (2 September 2015)

  • #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)

Version 1.2 (2 July 2015)

Version 1.1 (18 March 2015)

Version 1.0 (26 November 2014)

No new features or bugfixes, but it's about time to pump Slugify to v1.0., (*61)

Version 0.11 (23 November 2014)

  • #49 Add Zend Framework 2 integration (by acelaya)

Version 0.10.3 (8 November 2014)

Version 0.10.2 (18 October 2014)

Version 0.10.1 (1 September 2014)

Version 0.10.0 (26 August 2014)

Version 0.9 (29 May 2014)

  • #28 Add Symfony2 service alias and make Twig extension private (by Kevin Bond)

Version 0.8 (18 April 2014)

  • #27 Add support for Arabic characters (by Davide Bellini)
  • Added some missing characters
  • Improved organisation of characters in Slugify class

Version 0.7 (4 April 2014)

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., (*62)

  • #23 Added Symfony2 service
  • #24 Added Twig extension
  • #25 Added Silex service provider

Version 0.6 (2 April 2014)

Version 0.5 (28 March 2014)

Version 0.4.1 (9 March 2014)

Version 0.4 (17 January 2014)

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., (*63)

Version 0.3 (12 January 2014)

  • #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)

Authors

Support for Chinese is adapted from jifei/Pinyin with permission., (*64)

Slugify is a project of Cocur. You can contact us on Twitter: @cocurco, (*65)

Support

If you need support you can ask on Twitter (well, only if your question is short) or you can join our chat on Gitter., (*66)

Gitter, (*67)

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., (*68)

You always can help me (Florian, the original developer and maintainer) out by sending me an Euro or two., (*69)

License

The MIT License (MIT), (*70)

Copyright (c) 2012-2017 Florian Eckerstorfer, (*71)

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:, (*72)

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software., (*73)

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., (*74)

The Versions

04/04 2014
02/04 2014

v0.6

0.6.0.0

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.3

 

The Development Requires

slug slugify

28/03 2014

v0.5

0.5.0.0

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.3

 

The Development Requires

slug slugify

09/03 2014

v0.4.1

0.4.1.0

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.3

 

The Development Requires

slug slugify

17/01 2014

0.4.x-dev

0.4.9999999.9999999-dev

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.3

 

The Development Requires

slug slugify

17/01 2014

v0.4

0.4.0.0

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.3

 

The Development Requires

slug slugify

12/01 2014

0.3.x-dev

0.3.9999999.9999999-dev

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.3

 

The Development Requires

slug slugify

12/01 2014

v0.3

0.3.0.0

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.3

 

The Development Requires

slug slugify

22/06 2013

v0.2.3

0.2.3.0

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.8

 

slug slugify

08/03 2013

v0.2.2

0.2.2.0

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.8

 

slug slugify

08/03 2013

v0.2.1

0.2.1.0

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.8

 

slug slugify

21/02 2013

v0.2

0.2.0.0

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.8

 

slug slugify

23/03 2012

v0.1.1

0.1.1.0

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.8

 

slug slugify

23/03 2012

v0.1

0.1.0.0

Converts a string into a slug.

  Sources   Download

MIT

The Requires

  • php >=5.3.8

 

slug slugify