Overview
This blog describes the technique to sort the French words(special alphabet characters). To do this we need to use a php library called INTL. This library includes a class “Collator” which enables us to achieve this task. I did some R&D and came to the conclusion that we need to install a php library. So let’s see how we can implement it in any project.
Installation
This library is easy to install. I was working on a Ubuntu system so here is the support stackoverflow link for installation. I just ran two commands and boooom….it’s done! The commands I have used are as follows.
sudo apt-get install php7.2-intl // your Php version sudo service apache2 restart
Note: Do not forget to restart the Apache server. Please check whether that, the library is ready or not by using the “phpinfo()” function.
Code snippets
Once everything is done, you will be able to use the “Collator” class in your .php files. Please check the following code snippets and the actual difference:
$mix_words = array('cote','À bientôt', 'coté', 'abattre', 'common'); sort( $mix_words ); // this will give you output like following // abattre, common, cote, coté, À bientôt
The default Php “sort()” function will consider french accented words as special characters and it will put all those words at the last index. In short, it won’t work.
Now let’s see the magic snippet! ?
$mix_words = array('cote','À bientôt', 'coté', 'abattre', 'common'); $collator = new Collator('fr_FR'); $collator->asort($mix_words); // the out put will be // abattre, À bientôt, common, cote, coté
- Create an object of the Collator class and use the asort function. 😉
- Just put your mixed words array in the assort function and see the result.
Just put your mixed words array in the assort function and see the result.
Note: you can use different locales like “de_DE.UTF8” for German, “fr_FR ” for French, etc. Here are the support links for both locales “fr_FR”, “de_DE”.
Conclusion
Every time our clients come up with different expectations and new things. While I was working on a multilingual project, the client said that it was very important to display all the mixed words in a proper sorting format. I spent a few minutes on it and got the solution. I hope this blog will help the communities which are working on multilingual projects. To sum up, we feel that the English language is dominating the world. However, I feel that sometimes we have to give support to the other languages because everyone knows something but nobody knows everything!
Happy Coding! ?