Kareem JO
Kareem JO

Reputation: 191

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'
?>

Upvotes: 5

Views: 6368

Answers (2)

Anas Naim
Anas Naim

Reputation: 313

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

Upvotes: 6

ausi
ausi

Reputation: 7413

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

Upvotes: 5

Related Questions