0

I'm creating an image upload form and I need to name the images the user's name and dog's name when it is added into my database, and added into my upload folder.

I currently have this working like this:

  1. I use the POST method at the top of my script to pull in the user name and dog name from the form.
  2. I then use that info to rename the file/image being uploaded
  3. Then I insert into my database

$user_name = $_POST['user_name'];
$dog_name  = $_POST['dog_name'];

$file_name = $imgDir . $user_name .'-'. $dog_name .'-'. $random_number . $ext;

When inserting into the table I use the following:

'file_name' => str_replace("../path/to/images/", "", $file_name),

The current output of the file name is like this: John-Fido-123456.jpg

How would I remove the spaces in file name if the user entered their last name like this?

John Doe-Fido Doe-123456.jpg


Update: Thanks to @HiDeo i used the dup link that he posted and was able to figure it out like this.

Using the Post method to grab the names I needed. I striped the white spaces like so and it worked on the file name in the database and the actual image in the folder.

$user_name  =   $_POST['user_name'];
$dog_name   =   $_POST['dog_name'];


$user_name = preg_replace('/\s+/', '', $user_name);
$dog_name  = preg_replace('/\s+/', '', $dog_name );
daugaard47
  • 1,726
  • 5
  • 39
  • 74

1 Answers1

5

You can use:

'file_name' => str_replace(" ", "", $file_name);

Well, this will replace all white-spaces with nothing... (i.e. Remove all whitespace)...

The code suggestion is based on your code

Hope this helps...:)

Aayush Sinha
  • 377
  • 4
  • 18
  • That works, but leaves the full path to the image. If I do this: `'file_name' => str_replace("../path/to/image/"," ", "", $file_name),` everything goes blank in my file name field in my database..? – daugaard47 Jul 31 '16 at 06:42
  • No, you should try this solution after that line... – Aayush Sinha Jul 31 '16 at 06:44
  • Hmmm... No still leaves the path to the file. Also the images still have a space between the First and Last Name, when I check the image in the folder. `'file_name' => str_replace("../path/to/image/", "", $file_name), 'file_name' => str_replace(" ", "", $file_name),` – daugaard47 Jul 31 '16 at 06:50
  • Did you use it this way? `$filename = str_replace(" ", "", $file_name);` – Aayush Sinha Jul 31 '16 at 14:58
  • No, if you see in my original post I updated it and added in my solution to the problem. Although your way removed the white spaces in the file name going to the database, it left the white spaces in the file name going into the image folder. Also left the path to the image in the database. +1 though for helping. – daugaard47 Jul 31 '16 at 15:35