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

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

Patricia Arquette
Release: 2024-12-12 15:39:12
Original
650 people have browsed it

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

Generate URL-Friendly Slugs from Unicode Strings in PHP

Creating slugs from Unicode strings is crucial for generating SEO-friendly URLs. In PHP, a slugification function can be implemented to convert strings like "Andrés Cortez" to "andres-cortez."

To achieve this, consider using a more efficient approach compared to repetitive replacements. The following function provides a solution:

public static function slugify($text, string $divider = '-')
{
  // Replace non-letter or digits with the specified divider
  $text = preg_replace('~[^\pL\d]+~u', $divider, $text);

  // Transliterate to US-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);

  // Convert to lowercase
  $text = strtolower($text);

  // Default to 'n-a' if the slug is empty
  if (empty($text)) {
    return 'n-a';
  }

  return $text;
}
Copy after login

This function follows a structured approach:

  • Non-letter or digit characters are replaced with the specified divider.
  • Unicode characters are transliterated to US-ASCII for compatibility.
  • Unwanted characters are removed, such as spaces and special characters.
  • Leading and trailing dividers are trimmed, and duplicate dividers are eliminated.
  • The slug is converted to lowercase.
  • An empty slug defaults to 'n-a' to avoid empty URLs.

By utilizing this efficient slugification function, you can effortlessly generate URL-friendly slugs from Unicode strings in your PHP applications.

The above is the detailed content of How to Create SEO-Friendly URL 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