Slug PHP Function Example - slugify($string)

  • 08-10-2022
  • 1433
  • PHP
  • Haresh Chauhan

This tutorial will help you to make a slug from the string PHP. convert the string or title into the slug using the PHP function. I am providing a slug convert PHP function using this function you can make your text, title, and name into a slug.

This is important while you make your site SEO-friendly URL, so that time you are required to make your site page title into a slug, therefore, you require a function that converts your title into a slug.

Below slugify() function will help you to convert your title into a slug, You just pass a string as the first argument in the function. also, the second argument is optional, this fir the deviation of your string with the symbol.

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

We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :