Home > Backend Development > PHP Tutorial > How to Generate URL-Friendly Slugs from Unicode Strings in PHP?

How to Generate URL-Friendly Slugs from Unicode Strings in PHP?

Susan Sarandon
Release: 2024-12-11 12:09:10
Original
638 people have browsed it

How to Generate URL-Friendly Slugs from Unicode Strings in PHP?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template