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.
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.
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