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'
?>
A slug is a human-readable, unique identifier, used to identify a resource instead of a less human-readable identifier like an id .
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' ?>
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 .
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With