Removing Spaces From A Text Field

Discussion in 'PHP' started by timallard, Jan 29, 2008.

  1. #1
    Hello,

    I have a text field, which creates a file name for an XML file. It then takes that XML file and throws it on my server to download.

    When a user types the file name with spaces, it throws the application off.
    I need a simple function that removes spaces from words. e.g.

    Before: My File Name
    After: MyFileName

    I know its a simple solution,
    Thank You!
    -Tim
     
    timallard, Jan 29, 2008 IP
  2. Possibility

    Possibility Peon

    Messages:
    350
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Try str_replace()

    $text = "my file name";
    $text = str_replace(" ", "", $text);
    PHP:
     
    Possibility, Jan 29, 2008 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    I would suggest using preg_replace() because the user might enter other characters that are not allowed in file names.
    
    
    $name = preg_replace('~[^\w-\.]+~', '', $name);
    
    PHP:
    This for example would replace everything except alphanumeric characters, dashes, underscores, and periods.
     
    nico_swd, Jan 29, 2008 IP
  4. timallard

    timallard Well-Known Member

    Messages:
    1,634
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    158
    #4
    Thank you both!
     
    timallard, Jan 29, 2008 IP