http://vria.eu SL

Wellcome to my professional blog dedicated to interesting things in programming, web-development and design patterns.

Library and Symfony bundle to remove diacritic signs form strings

Apr 24, 2016 php symfony

This blogpost is a presentation of tiny PHP library that offers an easy way to remove accent signs from characters. In addition, a Symfony integration allows you to use Twig filter to delete diacritic signs in templates.

no_diacritic.png

For various reasons you can run into situation where you have to get a clean string without accents. Firstly, it might be an input query like "chèvre ou bœuf" to be converted into "chevre ou boeuf", secondly, it could be an output string like "côté de veau cuit à cœur" that you want to display as "cote de veau cuit a coeur".

Would not it be nice to have a simple function in php that sanitizes stings from accent signs? Here it is: https://github.com/vria/nodiacritic.

Installation gets easier if you use composer:


composer require vria/nodiacritic

Once installation is finished, you can use the function filter of NoDiacritic class:


use VRia\Utils\NoDiacritic;

$noAccentsRevolution = NoDiacritic::filter("Révolution française");

//Revolution francaise

The library properly treats German and Danish words if you pass an appropriate locale. In fact, function filter has two arguments:


filter($string, $locale = null)

The first argument is a string to be cleaned, and a second one is a locale, which is a standardized language name ISO 639-1. For example:


$noAccentsNiceStreet = NoDiacritic::filter("Schöne straße", "de");

//Schoene strasse

Moreover, there is NoDiactiticBundle that integrates the library above into Symfony https://github.com/vria/nodiacritic-bundle. In particular, bundle adds nodiacritic filter to your templates:


{{ "Révolution française"|nodiacritic }}

There is no need to specify locale because bundle knows it from the current Request. If for some reason desirable locale differs from the Request's one there is a possibility to pass it:


Ceci est une phrase allemande sans caractères spéciaux: {{ "Schöne straße"|nodiacritic("de") }}

{# Ceci est une phrase allemande sans caractères spéciaux: Schoene strasse #}

Also you can get the filter function from a controller:


$this->get('nodiacritic')->filter('Révolution française');

Nevertheless I recommend using NoDiacritic::filter function directly.

I hope that these libraries will make your life esier.