Home >Backend Development >PHP Tutorial >How to Efficiently Create Slugs from Unicode Strings in PHP?

How to Efficiently Create Slugs from Unicode Strings in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-09 10:02:07789browse

How to Efficiently Create Slugs from Unicode Strings in PHP?

Creating Slugs for Unicode Strings in PHP

When working with Unicode strings, it becomes necessary to create slugs, which are URL-friendly strings representing the original content. This process involves transliterating, removing unwanted characters, and converting the string to lowercase.

Implementing a slugify Function

To create a slugify function in PHP, follow this approach:

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;
}

Example Usage

To use this function, simply call it as follows:

$slug = slugify('Andrés Cortez');
echo $slug; // andres-cortez

This provides a more efficient and concise method for creating slugs from Unicode strings, eliminating the need for lengthy replacements.

The above is the detailed content of How to Efficiently Create Slugs from Unicode Strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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