Git Product home page Git Product logo

slugify's Introduction

cocur/slugify

Converts a string into a slug.

Build Status Windows Build status Scrutinizer Quality Score Code Coverage

Latest Release MIT License Total Downloads

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.
  • 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:

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:

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

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:

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

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.

$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"

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.

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

$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-"

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:

$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"

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

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

// app/AppKernel.php

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            // ...
            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:

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

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:

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

{{ '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.

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:

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:

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

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.

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.

/** @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 [
    "cocur_slugify" => [
        "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:

# 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");
    }
}

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

{$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", [new SlugifyHelper(Slugify::create()), "slugify"]);

Slim 3

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>

League

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

Change Log

Version 4.5.1 (16 September 2023)

  • Drop support for PHP 7 and fix version constraints
  • Replaces v4.5.0

Version 4.5 (16 September 2023)

  • #327 Add Korean to default ruleset
  • Replaced by v4.5.1 since this release breaks compatibility with PHP 7

Version 4.4.1 (17 September 2023)

  • Remove PHP 7 from compatibility list
  • Replaces v4.4.0

Version 4.4 (5 August 2023)

  • #320 Add Korean (by MrMooky)
  • #322 Add types to avoid PHP 8.2 deprecation warning (by antoniovj1)
  • Replaced by v4.4.1 since this release broke compatibility with PHP 7

Version 4.3 (7 December 2022)

Version 4.2 (13 August 2022)

Version 4.1 (11 January 2022)

Support for Symfony 6.

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.

Support for PHP 5, Twig 1 and Silex is dropped.

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.

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.

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

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.

Slugify is a project of Cocur. You can contact us on Twitter: @cocurco

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.

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.

License

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.

slugify's People

Contributors

acelaya avatar bartko-s avatar cvetan avatar fabienpapet avatar florianeckerstorfer avatar franmomu avatar gabiudrescu avatar gromnan avatar irfanevrens avatar ivoba avatar jakefr avatar julienfalque avatar kafoso avatar kbond avatar kubawerlos avatar localheinz avatar lookyman avatar luca-alsina avatar mac2000 avatar malenkiki avatar mhujer avatar michalskop avatar rusipapazov avatar samnela avatar seldaek avatar shakaran avatar snapshotpl avatar thomaslandauer avatar wandersonwhcr avatar yankl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

slugify's Issues

Minimum PHP version 5.5.9

In 77e3f22 , the minimum PHP version was set to 5.5.9. We're having trouble now because all our production servers are running CentOS with 5.4.*.

Is there any chance that can be reverted?

Feedback for 2.0 release

I want to release 2.0 pretty soon but I would like to gather some feedback before. Please let me know if you already use the 2.0 (that is, the master branch) in your code or if you tried to use it and it didn't work out.

I am especially interested in the various integrations. Tests are one thing, using it in real world code another one and I don't have time (and, frankly, expertise for some of the integrations) to test them in real examples.

Any help to get 2.0 out of the door is highly appreciated.

PSR for Slugifier/Urlizer Interface

Hi,

Just to let you know, we are making a proposal for the creation of a standard slugifier/urlizer interface at fig-standards:

https://github.com/php-fig/fig-standards/pull/100

There is also a mailing list post:

https://groups.google.com/forum/?fromgroups=#!topic/php-fig/J-6s9Wlyk-A

It would be cool if this proposal goes through and we can apply the interface to this library :)

Cheers

Dan

slug() regex cleanup

This

const LOWERCASE_NUMBERS_DASHES = '/([^A-Za-z0-9]|-)+/';

would work just the same if rewritten as

const LOWERCASE_NUMBERS_DASHES = '/([^A-Za-z0-9])+/';

or even clearer,

const LOWERCASE_NUMBERS_DASHES = '/([^A-Za-z0-9]+)/';

The hyphen at the end seems superfluous given that the character class match [^a-zA-Z0-9] is already capturing the hyphen.

Twig Bridge - no functionality to add rule

As per the documentation, slugify has a method addRule which we can call to add custom rules, same is not available via twig bridge.
We have a use-case where we want to use the filter with a custom filter. So I started looking at the code base and seems it can be done with a small change to the SlugifyExtension. I have got it working on my environment and just wanted to your views before I submit a pull request.
Use-Case:
We have words like "Snacks & Bars", which we want to be converted to "snacks-and-bar". Using Slugify class it can be easily done by using the method addRule('&', 'and'), but we are using it in the twig as a filter.

So the change will be as follows:

public function slugifyFilter($string, $separator = null, $newRules = [])
    {
	    if (! empty($newRules)) {
		    $this->slugify->addRules($newRules);
	    }
	    return $this->slugify->slugify($string, $separator);
    }

Regards,

create new version tag 0.2.3

Can you create a new tag as stable version 0.2.3 to include the changes from the last 6 months.

These changes are missing for bundles that require slugify with ~0.2 because they end up in tag 0.2.2.

I assume the changes are stable.

Turkish and German characters Problem

  • German:
    • Ö => OE
    • Ü => UE
    • ö => oe
    • ü => üe
  • Turkish:
    • Ö => O
    • Ü => U
    • ö => o
    • ü => u

How to solve this problem ?

Example;

  • "Öğretmen" the Turkish word:
    • Öğretmen => oegretmen this convert false
    • Öğretmen => ogretmen this convert true

Feature request: getRules() method

We (try to) use slugify, next to url-slugs, to also create "safe" filenames and some titles, which allow uppercase characters. The slugify rules already have conversions for uppercase, like "Ö" => "O", but these are discarded with two strtolower() calls.

  • Can we have access to the protected rules by implementing a getRules() method,
    so that i can do my own strtr($str, $slugify->getRules()) conversions based on slugify,
    when i need to keep uppercase characters.
    public function getRules()
    {
        return $this->rules;
    }
  • Alternatively suggestion, have an extra $strict=true parameter on slugify()
    to allow more control over uppercase conversion.
    public function slugify($string, $separator = '-', $strict = true)
    {
        $string = strtr($string, $this->rules);
        if ($strict) $string = strtolower($string);
        $string = preg_replace($this->regExp, $separator, $string);
        if ($strict) $string = strtolower($string);

        return trim($string, $separator);
    }

    // ...

    $in = "Et le proxénète s'est avancé, à la Barre";
    $var = $slugify->slugify($in);
    // et-le-proxenete-s-est-avance-a-la-barre

    // also allow uppercase, spaces and some chars, remove others
    $slugify->setRegExp('/[^a-zA-Z0-9_., -]+/');
    $var = $slugify->slugify($in, '', false);
    // Et le proxenete sest avance, a la Barre

Works great with Slim 3

Sample Slim/3 integration using the below 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()));
    //$view->addExtension(new Twig_Extension_Debug());
    return $view;
};

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

Laravel Bridge not loading via Composer

Just tried installing slugify with Composer for Laravel 4 and the Laravel Bridge folder isn't being installed via composer.

Am guessing a new git tag is needed to load it into Composer?

Core functionality for earlier PHP versions?

I'm maintaining a project on PHP 5.3, and I was able to make the Slugify::slugify() method work by converting arrays to old syntax in Slugify.php.

I realize that some of the framework integrations require a newer version of PHP, but if the core functionality doesn't, why not allow earlier versions?

Bug on Swedish ruleset

I think there is a bug in the Swedish ruleset. In both the DefaultRuleProvider and swedish.json file we have the following problems:

  • Å and å is missing
  • ö is changed to "ö" (instead of "o")

It looks like this in DefaultRuleProvider:
'swedish' => array ( 'Ä' => 'A', 'Ö' => 'O', 'ä' => 'a', 'ö' => 'ö', ),

And like this in swedish.json:
{ "Ä": "A", "Ö": "O", "ä": "a", "ö": "ö" }

I could create a pull request I guess. Im just not sure if Im missing something obvious here. Let me know if you want me to send a PR. :)

Swedish transliteration

Hi! When we transliterate the Swedish characters å, ä and ö, we use a, a and o. I see you're using the German system of aa, ae and oe for Slugify.

Not really sure how best to solve this but I thought I'd raise the issue.

Arabic Slug

$string = 'وزيرة شؤون الشباب والرياضة';

$slugify = new \Cocur\Slugify\Slugify(); 
$slugify->activateRuleset('arabic'); 
echo $slugify->slugify($string);

The Echo Show this : ozyr-sh-on-lshb-b-o-lry-d

whish is not correct athe slug should be :

وزيرة-شؤون-الشباب-و-الرياضة

That's all

I tried As per the customizeSlugEngine docs, in the model that uses Sluggable, adding:

public function customizeSlugEngine(Slugify $engine, $attribute)
{
    $engine->activateRuleset('arabic');
    return $engine;
}

And the same Problem

Need for a constructor

Hi there,
I sent #6 but I was thinking if there is a strong need to have an instance here.
As a user I would only care about having Slugify::slugify($string) and not care about implementation, because I'd expect it to default to the best mode available.
Do you know of use cases where the user would explicitly need a specific implementation?

Laravel and bindShared

Can you release new version, so we can use Slugify with newest version of Laravel?

Thank you in advance!

Version 1.4.1

Does your newest release tag refer to the correct commit?

Current: 16cdd7e
Master merge: 5b9c427

With v1.4.1 - referring to 16cdd7e - i get errors which i dont get with the master merge. (preg_replace(): Delimiter must not be alphanumeric or backslash at Slugify.php:804)

slugify fail for long string of other language e.gMarathi,Hindi,kannada etc.....

for this msg
11:50AM - बांगलादेशमध्ये सलग तिसऱ्या वर्षी आशिया कप टी-ट्वेंटी स्पर्धेचे आयोजन करण्यात आले असून २४ फेब्रुवारी ते ६ मार्च दरम्यान ही स्पर्धा होणार आहे.
11:46AM - नगरमध्ये त्रिमूर्ती कॉलेजमधील १२ वीच्या विद्यार्थीनीची आत्महत्या, वर्गातच लावून घेतला गळफास
11:38AM - बँकॉकमधील नृत्यस्पर्धेसाठी मुख्यमंत्र्याकडून देण्यात आलेला ८ लाख रुपयांचा निधी कलावंतांनी परत दिला आहे.11:50AM - बांगलादेशमध्ये सलग तिसऱ्या वर्षी आशिया कप टी-ट्वेंटी स्पर्धेचे आयोजन करण्यात आले असून २४ फेब्रुवारी ते ६ मार्च दरम्यान ही स्पर्धा होणार आहे.
11:46AM - नगरमध्ये त्रिमूर्ती कॉलेजमधील १२ वीच्या विद्यार्थीनीची आत्महत्या, वर्गातच लावून घेतला गळफास
11:38AM - बँकॉकमधील नृत्यस्पर्धेसाठी मुख्यमंत्र्याकडून देण्यात आलेला ८ लाख रुपयांचा निधी कलावंतांनी परत दिला आहे.11:50AM - बांगलादेशमध्ये सलग तिसऱ्या वर्षी आशिया कप टी-ट्वेंटी स्पर्धेचे आयोजन करण्यात आले असून २४ फेब्रुवारी ते ६ मार्च दरम्यान ही स्पर्धा होणार आहे.
11:46AM - नगरमध्ये त्रिमूर्ती कॉलेजमधील १२ वीच्या विद्यार्थीनीची आत्महत्या, वर्गातच लावून घेतला गळफास
11:38AM - बँकॉकमधील नृत्यस्पर्धेसाठी मुख्यमंत्र्याकडून देण्यात आलेला ८ लाख रुपयांचा निधी कलावंतांनी परत दिला आहे.11:50AM - बांगलादेशमध्ये सलग तिसऱ्या वर्षी आशिया कप टी-ट्वेंटी स्पर्धेचे आयोजन करण्यात आले असून २४ फेब्रुवारी ते ६ मार्च दरम्यान ही स्पर्धा होणार आहे.
11:46AM - नगरमध्ये त्रिमूर्ती कॉलेजमधील १२ वीच्या विद्यार्थीनीची आत्महत्या, वर्गातच लावून घेतला गळफास
11:38AM - बँकॉकमधील नृत्यस्पर्धेसाठी मुख्यमंत्र्याकडून देण्यात आलेला ८ लाख रुपयांचा निधी कलावंतांनी परत दिला आहे.11:50AM - बांगलादेशमध्ये सलग तिसऱ्या वर्षी आशिया कप टी-ट्वेंटी स्पर्धेचे आयोजन करण्यात आले असून २४ फेब्रुवारी ते ६ मार्च दरम्यान ही स्पर्धा होणार आहे.
11:46AM - नगरमध्ये त्रिमूर्ती कॉलेजमधील १२ वीच्या विद्यार्थीनीची आत्महत्या, वर्गातच लावून घेतला गळफास
11:38AM - बँकॉकमधील नृत्यस्पर्धेसाठी मुख्यमंत्र्याकडून देण्यात आलेला ८ लाख रुपयांचा निधी कलावंतांनी परत दिला आहे.11:50AM - बांगलादेशमध्ये सलग तिसऱ्या वर्षी आशिया कप टी-ट्वेंटी स्पर्धेचे आयोजन करण्यात आले असून २४ फेब्रुवारी ते ६ मार्च दरम्यान ही स्पर्धा होणार आहे.
11:46AM - नगरमध्ये त्रिमूर्ती कॉलेजमधील १२ वीच्या विद्यार्थीनीची आत्महत्या, वर्गातच लावून घेतला गळफास
11:38AM - बँकॉकमधील नृत्यस्पर्धेसाठी मुख्यमंत्र्याकडून देण्यात आलेला ८ लाख रुपयांचा निधी कलावंतांनी परत दिला आहे.11:50AM - बांगलादेशमध्ये सलग तिसऱ्या वर्षी आशिया कप टी-ट्वेंटी स्पर्धेचे आयोजन करण्यात आले असून २४ फेब्रुवारी ते ६ मार्च दरम्यान ही स्पर्धा होणार आहे.
11:46AM - नगरमध्ये त्रिमूर्ती कॉलेजमधील १२ वीच्या विद्यार्थीनीची आत्महत्या, वर्गातच लावून घेतला गळफास
11:38AM - बँकॉकमधील नृत्यस्पर्धेसाठी मुख्यमंत्र्याकडून देण्यात आलेला ८ लाख रुपयांचा निधी कलावंतांनी परत दिला आहे.

i am using cocur/slugify in laravel 5.1
so It fail at this line for above msg
preg_replace($this->regExp, $separator, $string);

Tag new release for features

Can you create a new release for the new lowercase options?
That way we can composer update our projects.
Thank you.

Turkish problem

Hey,

Seems like some Turkish letters fall into German:

Türkiye Kupasi => tuerkiye-kupasi

While it should be turkiye-kupasi. Same problem with ö which should fall into o.

Not sure, but it seems Turkish should go to a ruleset.

Conflicting replacements for some languages

I realised that there are some conflicting replacements in the Slugify class. I think these are specially the Esperanto characters, since the characters are also used in other languages. For example,

Slugify.php L:60

'ĉ' => 'c',

Slugify.php L:414

'ĉ' => 'cx',

Should we remove Esperanto or provide some switch for users to select which version they want?

Empty regexp error when using option "lowercase" to false

When specifiying the lowercase option

$slugify = new Slugify(array('lowercase' => false)); // keep uppercase letters
$this->name = $slugify->slugify("Annonce: Jean Claude vends dame", '_');

An error is thrown:

Warning: preg_replace(): Empty regular expression

Specifying a regexp as second option does not fix the issue either.

ServiceProviderInterface not found

hey guys, any guess why I got this error ?

I am on Silex 2 and Slugify 2.1

Fatal error: Interface 'Silex\ServiceProviderInterface' not found in /var/www/vendor/cocur/slugify/src/Bridge/Silex/SlugifyServiceProvider.php on line 28

just notice this interface is related to the silex application. the declaration I have in my codebase uses the pimple declaration. this is a version incompatibility ?

Turn ampersand (&) into word equivalents, e.g. "and"

To make a URL truly readable, it would be a great enhancement, if the ampersand symbol - & - were to be converted into its textual counterpart, e.g.:

  • da: og
  • de: und
  • en: and
  • es: y
  • fr: et
  • sv: och

... and so on.

The rulesets is a nudge in this direction. However, this logic only allows for flat character conversion, e.g. "x" to "y". Not conversions per locale.

In English (en), a URL like "Boys & Girls" would then become "boys-and-girls", rather than "boys-girls" as produced by the current logic.

Implementation

A SymbolRule class could be injected into the Slugify logic. This makes Slugify backwards compatibility (i.e. not breaking existing implementations/builds).

If said rule exists as a new variable inside the Slugify class, the logic contained within the SymbolRule class would be applied before the $separator (default "-"), e.g. converting "&" to their word equivalents.

A generic SymbolRule class could look something like this, to allow for other symbols than "&".

Example:

namespace Cocur\Slugify;

class SymbolRule {
    protected $rules = array();

    public function setRule($symbol, array $localesToWords){
        $this->rules[$symbol] = $localesToWords;
        return $this;
    }

    public function processString($str, $localeCode){
        if ($this->rules) {
            foreach ($this->rules as $symbol => $localesToWords) {
                if (array_key_exists($localeCode, $localesToWords)) {
                    $word = $localesToWords[$localeCode];
                    $str = str_replace($symbol, $word, $str);
                }
            }
        }
        return $str;
    }
}

Asserting to validate my logic:

$symbolRule = new SymbolRule("da");
$symbolRule->setRule("&", [
    "da" => "og",
    "en" => "and",
]);
$strEn = $symbolRule->processString("Boys & Girls", "en");
$strDa = $symbolRule->processString("Drenge & Piger", "da");

assert($strEn === "Boys and Girls");
assert($strDa === "Drenge og Piger");

And finally, inserted into the Slugify class:

// ...
class Slugify implements SlugifyInterface
{
    // ...
    protected $symbolRule;

    // ...

    public function setSymbolRule(\Cocur\Slugify\SymbolRule $symbolRule){
        $this->symbolRule = $symbolRule;
        return $this;
    }

    // ...

    public function public function slugify($string, $separator = '-'){
        $string = strtr($string, $this->rules);
        // New [
        if ($this->symbolRule) {
            $string = $this->symbolRule->processString($string);
        }
        // ]
        if ($this->options['lowercase']) {
                $string = mb_strtolower($string);
        }
        $string = preg_replace($this->regExp, $separator, $string);
        return trim($string, $separator);
    }
}

Yay or Nay?

typo seperator

seperator => separator
on the README and maybe other locations.

Lowercase option issue

Hi,

when I use lowercase option on the fly, i got this two warnings :

Warning: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array in /scripts/vendor/cocur/slugify/src/Slugify.php on line 103                                                                                                                                                                           
Warning: trim() expects parameter 2 to be string, array given in /scripts/vendor/cocur/slugify/src/Slugify.php on line 105

Result, the username isn't "slugified". Without this option, it works well but slugify convert the username to lowercase, which is not expected in my case.

Code :

use Cocur\Slugify\Slugify;
$slugify = new Slugify();

[...]

if(!preg_match('/^[a-zA-Z0-9-_]+$/', $user['username'])) {
    $username = $slugify->slugify($user['username'], ['lowercase' => false]);
    $query = RunPreparedQuery($dbFluxbb, [':username' => $username], "SELECT id FROM {$dbFluxbbPrefix}users WHERE BINARY username=:username");
    $row = $query->fetch(PDO::FETCH_ASSOC);
    [...]
}

Environment :

  • OS: Alpine Linux 3.4
  • PHP version : 7.0.11
  • Extensions enabled : phar, openssl, pdo_mysql, iconv, mbstring, dom, curl, intl, json, xsl, zlib, gd

Thanks.

Vietnamese support

Vietnamese is similar to latin alphabet expect some hyphen and characters.
I have a function (search it on google) which replace vietnamese special characters with the similar in Latin characters.
Hope you'll add vietnamese to supported list
function removesign($str)
{
$coDau=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă","ằ","ắ"
,"ặ","ẳ","ẵ","è","é","ẹ","ẻ","ẽ","ê","ề","ế","ệ","ể","ễ","ì","í","ị","ỉ","ĩ",
"ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
,"ờ","ớ","ợ","ở","ỡ",
"ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
"ỳ","ý","ỵ","ỷ","ỹ",
"đ",
"À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
"È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
"Ì","Í","Ị","Ỉ","Ĩ",
"Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
,"Ờ","Ớ","Ợ","Ở","Ỡ",
"Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
"Ỳ","Ý","Ỵ","Ỷ","Ỹ",
"Đ","ê","ù","à");
$khongDau=array("a","a","a","a","a","a","a","a","a","a","a"
,"a","a","a","a","a","a",
"e","e","e","e","e","e","e","e","e","e","e",
"i","i","i","i","i",
"o","o","o","o","o","o","o","o","o","o","o","o"
,"o","o","o","o","o",
"u","u","u","u","u","u","u","u","u","u","u",
"y","y","y","y","y",
"d",
"A","A","A","A","A","A","A","A","A","A","A","A"
,"A","A","A","A","A",
"E","E","E","E","E","E","E","E","E","E","E",
"I","I","I","I","I",
"O","O","O","O","O","O","O","O","O","O","O","O"
,"O","O","O","O","O",
"U","U","U","U","U","U","U","U","U","U","U",
"Y","Y","Y","Y","Y",
"D","e","u","a");
return str_replace($coDau,$khongDau,$str);
}
Usage: removesign($str)
Ex: $str = 'tiếng việt rất khó'; #Vietnamese is very difficult
echo removesign($str); #'tieng viet rat kho'

Symfony integration - missing rulesets with default configuration

Hi,
since the feature to configure Slugify through the Symfony bundle configuration was added, the Slugify instance is now by default created without any ruleset, thus converting all special characters to just the separator.

The problem is that with default configuration (ie. no custom config in symfony) empty array of rulesets is passed to the constructor. However, the constructor then uses array_merge to merge this options with default options - but the array_merge merges just the first level of the $options, so the rulesets option is kept as and empty array.

regenerate rules

run generate-default.php to generate rules, because the bulgarian is missing
and in the rule file for bulgarian the last entry finishes with a comma - remove it

How to completely remove separators (dash, dots, spaces, etc)

Just for simplicity, can I set slugify to remove all separators (dash, dots, spaces, etc) and concatenate every word?

For example:

echo $slugify->slugify('A strange.example_user-name', '');

Does it return this (desirable) result?

astrangeexampleusername

compatibility with Silex 2

Current version is not compatible with Silex version 2. ServiceProviderInterface is no longer part of Silex 2. It is replaced with Pimple\ServiceProviderInterface. Only minor changes are needed to make it work. Question is, what about backward compatibility? Will new version support only Silex ^2.0 or earlier versions as well?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.