Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP slug function for all languages

I'm wondering if there is a simple function/code that can take care of creating a slug from a given string.

I'm working on a multilingual website (English, Spanish, and Arabic) and I'm not sure how to handle that for Spanish and Arabic specifically.

I'm currently using the below code from CSS-Tricks but it doesn't work for UTF-8 text.

<?php
function create_slug($string){
   $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
   return $slug;
}
echo create_slug('does this thing work or not');
//returns 'does-this-thing-work-or-not'
?>
like image 835
Kareem JO Avatar asked May 04 '14 12:05

Kareem JO


People also ask

What is a slug in PHP?

A slug is a human-readable, unique identifier, used to identify a resource instead of a less human-readable identifier like an id .

How get slug URL in PHP?

php function createUrlSlug($urlString) { $slug = preg_replace('/[^A-Za-z0-9-]+/', '-', $urlString); return $slug; } echo createUrlSlug('this is the example demo page'); // This will return 'this-is-the-example-demo-page' ?>

What is a URL slug?

A Slug is the unique identifying part of a web address, typically at the end of the URL. In the context of MDN, it is the portion of the URL following "<locale>/docs/". It may also just be the final component when a new document is created under a parent document; for example, this page's slug is Glossary/Slug .


2 Answers

I created the library ausi/slug-generator for this purpose.

It uses the PHP Intl extension, to translate between different scripts, which itself is based on the data from Unicode CLDR. This way it works with a wide set of languages.

You can use it like so:

<?php
$generator = new SlugGenerator;

$generator->generate('English language!');
// Result: english-language

$generator->generate('Idioma español!');
// Result: idioma-espanol

$generator->generate('لغة عربية');
// Result: lght-rbyt
like image 172
ausi Avatar answered Oct 12 '22 10:10

ausi


If you would like to use the same text without translation

function slug($str, $limit = null) {
    if ($limit) {
        $str = mb_substr($str, 0, $limit, "utf-8");
    }
    $text = html_entity_decode($str, ENT_QUOTES, 'UTF-8');
    // replace non letter or digits by -
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
    // trim
    $text = trim($text, '-');
    return $text;
}

By: Walid Karray

like image 38
Anas Naim Avatar answered Oct 12 '22 11:10

Anas Naim