Home > Backend Development > PHP Tutorial > How Can I Create URL-Friendly Slugs from Strings using PHP?

How Can I Create URL-Friendly Slugs from Strings using PHP?

DDD
Release: 2024-12-07 05:53:16
Original
622 people have browsed it

How Can I Create URL-Friendly Slugs from Strings using PHP?

Creating URL-Friendly Slugs using PHP

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template