Back to Blog

How to Convert String to Slug in PHP

Handy function to create file names and URL slugs

Mar 5, 2023 Updated: Mar 5, 2023

Use the function below to convert string to URL friendly slug. I used this function to create filename that can be send as attachments with emails becauase filenames with spaces do not mostly send properly.

Here we are:

  1. removing spaces
  2. converting uppercase letters to lowercase letters
  3. replacing accented characters by equivalent standard characters and a bit more.
function createSlug($str, $delimiter = '-'){
    $slug = strtolower(trim(preg_replace('/[\s-]+/', $delimiter, preg_replace('/[^A-Za-z0-9-]+/', $delimiter, preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $str))))), $delimiter));
    return $slug;
} 
Contact

Got A Question For Me?

Feel free to ask anything directly on call or fill the form and I will contact back within few hours.