Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

slugify

> 编程语言
Open source

Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.

2.9K stars0 likes2 views
WebsiteGitHub

About

Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.

cocur/slugify

Converts a string into a slug. Developed by Florian Eckerstorfer in Vienna, Europe with the help of many great contributors.

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, 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.0 - 8.5.
  • 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:

bash
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.

Usage

Generate a slug:

php
use Cocur\Slugify\Slugify;

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

You can also change the separator used by Slugify:

php
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.

php
$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:

php
$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.

php
$slugify = new Slugify(["rulesets" => ["default", "turkish"]]);
$slugify->slugify("ä"); // -> "a"

You can find a list of the available rulesets in Resources/rules.

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.

php
$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.

php
$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.

php
$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.

php
$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.

php
$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:

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

You can also modify the separator this way:

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

You can even activate a custom ruleset without touching the default rules:

php
$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.

To add a new language you need to:

  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.

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.

The full Code of Conduct can be found here.

This project is no place for hate. If you have any problems please contact Florian: [email protected] ✌️‍

Further information

  • API docs

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:

Symfony 2

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

Symfony 3

php
// app/AppKernel.php

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

Symfony >= 4

php
// 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:

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

The bundle also provides an alias slugify for the cocur_slugify service:

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

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

php
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:

yaml
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).

twig
{{ 'Hällo Wörld'|slugify }}

If you use Twig outside of the Symfony framework you first need to add the extension to your environment:

php
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:

php
// 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.

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:

php
use Cocur\Slugify\Slugify;

$mustache = new Mustache_Engine([
    // ...
    "helpers" => [
        "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).

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

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

And add the facade into the "aliases" array:

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

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

php
$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.

Just enable the module in your configuration like this.

php
return [
    //...

    "modules" => [
        "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.

php
/** @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
<?php echo $this->slugify("Hällo Wörld"); ?>
<?php echo $this->slugify("Hällo Wörld", "_"); ?>

The service

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPlanguagelattenettephp

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言