Search code examples
phpimagepostslugslugify

Image POST php slug


I'm trying to make a slug name to image while upload, i was testing with str_replace but it doesn't work.

$_FILES['imgProfile']['name'] = str_replace("í", "i", $_FILES['imgProfile']['name']);

it returns something like: i?magen.png and doesn't upload the image.

I tried with this function and works, but removes the file extension.

function slugify($text)
{
  // replace non letter or digits by -
  $text = preg_replace('~[^\pL\d]+~u', '-', $text);

  // transliterate
  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

  // remove unwanted characters
  $text = preg_replace('~[^-\w]+~', '', $text);

  // trim
  $text = trim($text, '-');

  // remove duplicate -
  $text = preg_replace('~-+~', '-', $text);

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

  if (empty($text)) {
    return 'n-a';
  }

  return $text;
}

I only need to remove blank spaces with -and characters like á,é,í,ó,ú with a,e,i,o,u

If the file name is: "prueba para Guardar ímagen ñueva.png"

it must be: "prueba-para-guardar-imagen-nueva.png"

Thanks!


Solution

  • For your desired behavior you need to add to first row \.

    // replace non letter or digits by -
    $text = preg_replace('~[^\pL\d\.]+~u', '-', $text);
    

    and for third row too \.

    // remove unwanted characters
    $text = preg_replace('~[^-\w\.]+~', '', $text);