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
Release: 2024-12-09 10:02:07
Original
789 people have browsed it

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

Example Usage

To use this function, simply call it as follows:

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

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!

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