PHP function to make slug (URL string)
Creating a URL-friendly slug from a Unicode string like Andrés Cortez into andres-cortez is a common requirement when building applications that need to be accessible to international users. The core challenge lies in normalizing the text: converting accented characters to their ASCII equivalents and removing special symbols without breaking valid hyphens or underscores used as separators.
A naive approach might involve simple character replacement, but this fails immediately with Unicode normalization. Simply replacing 'é' with 'e' leaves you with inconsistent results if your input contains different ways of representing the same sound, such as Andr\xe9s versus Andrés. To handle this robustly, you must normalize the string using Unicode Normalization Form D (NFD) first. This decomposes characters into their base form and combining diacritical marks, allowing you to strip out the accents cleanly before converting to lowercase and replacing spaces.
Here is a practical implementation using PHP's built-in functions:
function gen_slug(string $text): string
{
// 1. Normalize the text (NFD form separates base char from accent)
$normalized = normalizerize($text, Normalizer::FORM_NFD);
// 2. Strip combining diacritical marks (the accents)
$stripped = preg_replace('/\pM/u', '', $normalized);
// 3. Remove non-alphanumeric characters except spaces and hyphens/underscores
// We keep hyphens and underscores because they are often desired in slugs
$cleaned = preg_replace('/[^a-z0-9\s_-]/ui', '', $stripped);
// 4. Replace spaces with hyphens and trim leading/trailing separators
return trim(preg_replace('/[ _]+/', '-', strtolower($cleaned)));
}
The critical detail here is the use of \pM in the regular expression. This property escapes specifically targets combining marks, which are the Unicode representation of accents. Without this step, you might end up with andres-cortez becoming andres-corte\u0301z, which looks correct visually but fails URL validation checks or database indexing.
One common pitfall is assuming that str_replace is sufficient for internationalization. If a user inputs "Café" and you simply replace 'é' with 'e', the logic breaks if the input contains a precomposed character versus a decomposed one. The Normalizer class handles this inconsistency automatically, ensuring that regardless of how the accent was encoded in the source string, the output remains consistent.
Another consideration is the handling of spaces versus hyphens. While str_replace(' ', '-') works for simple cases, it often leaves leading or trailing slashes or hyphens if the input started with a space (e.g., " John Doe"). The trim() function combined with the regex replacement ensures these edge cases are handled gracefully, preventing URL generation errors like /andres-cortez-.
For Laravel developers, this logic can be wrapped into a service class or an Eloquent accessor. If you are using Laravel, you might consider checking their documentation for existing helpers that abstract this complexity further, though understanding the underlying normalization is essential for debugging edge cases. The official guide on string manipulation often references these specific normalization steps when dealing with internationalized domains or slugs.
Performance-wise, the overhead of Normalizer::normalize is negligible for typical application payloads but becomes relevant in high-throughput environments processing millions of records. In such cases, caching the slug generation result or using a compiled regex pattern can offer marginal gains. However, for most web applications, the clarity and correctness gained by proper Unicode handling far outweighs micro-optimizations.
Ultimately, the goal is to produce a predictable, SEO-friendly string that represents the original intent without relying on fragile character-by-character mapping. By leveraging Unicode normalization properties, you ensure that your slugs remain consistent across different locales and encoding standards.