When building web applications, it's often necessary to convert strings into URL-friendly formats known as slugs. For instance, a string like "Andrés Cortez" should be converted to "andres-cortez" for use in a URL.
To achieve this, a custom PHP function can be employed:
public static function slugify($text, string $divider = '-') { // replace non letter or digits by divider $text = preg_replace('~[^\pL\d]+~u', $divider, $text); // transliterate $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); // remove unwanted characters $text = preg_replace('~[^-\w]+~', '', $text); // trim $text = trim($text, $divider); // remove duplicate divider $text = preg_replace('~-+~', $divider, $text); // lowercase $text = strtolower($text); if (empty($text)) { return 'n-a'; } return $text; }
This function utilizes a series of regular expressions and character conversions to transform the input string into a slug. It first replaces all non-alphanumeric characters with the specified divider. Then, it transliterates non-ASCII characters into their closest ASCII equivalents. Unwanted characters are removed, and the string is trimmed and converted to lowercase. Duplicate dividers are removed to ensure a clean slug.
By calling this slugify() function, developers can easily create slugs from Unicode strings, providing a straightforward solution for URL-friendly text in PHP applications.
The above is the detailed content of How Can I Create URL-Friendly Slugs from Strings using PHP?. For more information, please follow other related articles on the PHP Chinese website!