Creating URL-Friendly Slugs from Unicode Strings in PHP
Slugs are an important part of URL structure, making it easy for users to remember and navigate websites. For Unicode strings, generating slugs can be challenging due to the presence of special characters. This article explores a PHP function specialized in converting Unicode strings into URL-friendly slugs.
Question:
How to create a slug from a Unicode string, such as converting "Andrés Cortez" to "andres-cortez"?
Answer:
The following PHP function effectively handles this task:
public static function slugify($text, string $divider = '-') { // Replace non-alphanumeric characters with a divider $text = preg_replace('~[^\pL\d]+~u', $divider, $text); // Transliterate to ASCII $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); // Remove unwanted characters $text = preg_replace('~[^-\w]+~', '', $text); // Trim and remove duplicate dividers $text = trim($text, $divider); $text = preg_replace('~-+~', $divider, $text); // Lowercase and handle empty strings $text = strtolower($text); return empty($text) ? 'n-a' : $text; }
Based on the function provided, converting "Andrés Cortez" would return "andres-cortez" as the URL-friendly slug. This function comprehensively handles transliteration, character removal, trimming, and other steps necessary for slug creation.
The above is the detailed content of How to Generate URL-Friendly Slugs from Unicode Strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!