Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a PHP function to generate a pretty and valid URL from a natural text?

Tags:

php

I want to auto-generate a readable URL from any natural text, like this:

Latest article: About German letters - Handling äöü and ß!

would ideally be changed to this

latest-article-about-german-letters-handling-aou-and-ss.html

It should work for all latin based languages and I want to avoid any escaping.

I guess this could be achieved by regular expressions, but perhaps there's already a standard function available in PHP/PEAR/PECL.

like image 663
Daniel Rikowski Avatar asked Dec 07 '22 05:12

Daniel Rikowski


1 Answers

What you're looking for is slugify your text.

You can find snippets of code on the Internet such as this one that will do the trick:

/**
 * Modifies a string to remove al non ASCII characters and spaces.
 */
static public function slugify($text)
{
    // replace non letter or digits by -
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text);

    // trim
    $text = trim($text, '-');

    // transliterate
    if (function_exists('iconv'))
    {
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    }

    // lowercase
    $text = strtolower($text);

    // remove unwanted characters
    $text = preg_replace('~[^-\w]+~', '', $text);

    if (empty($text))
    {
        return 'n-a';
    }

    return $text;
}

From here.

like image 188
Guillaume Flandre Avatar answered May 13 '23 16:05

Guillaume Flandre