Generate URL-Friendly Slugs from Unicode Strings in PHP
Creating slugs from Unicode strings is crucial for generating SEO-friendly URLs. In PHP, a slugification function can be implemented to convert strings like "Andrés Cortez" to "andres-cortez."
To achieve this, consider using a more efficient approach compared to repetitive replacements. The following function provides a solution:
public static function slugify($text, string $divider = '-') { // Replace non-letter or digits with the specified divider $text = preg_replace('~[^\pL\d]+~u', $divider, $text); // Transliterate to US-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); // Convert to lowercase $text = strtolower($text); // Default to 'n-a' if the slug is empty if (empty($text)) { return 'n-a'; } return $text; }
This function follows a structured approach:
By utilizing this efficient slugification function, you can effortlessly generate URL-friendly slugs from Unicode strings in your PHP applications.
The above is the detailed content of How to Create SEO-Friendly URL Slugs from Unicode Strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!