Hi all, I want to allow uploading files to my webpage, but want the following to happen to the filename:

-ONLY LETTER AND NUMBERS
-REPLACE ALL SPACES WITH UNDERSCORES

I have the first one down but don't know how to replace all spaces with underscores, with what I have right now, it just gets rid of spaces:

ereg_replace("[^A-Za-z0-9]", "", $string);

Now, how can I replace spaces with underscores in that ereg_replace statement?

Thanks

    i'd use something like this:

    $string = preg_replace('/(\s)/', '_', $string);
    $string = preg_replace('/[^\w\.]/', '', $string);
    
      	$string = ereg_replace('[^a-zA-Z0-9 ]', '', $string);
      	$string = ereg_replace('[ ]+', '_', strtolower($string));
      

      That is what I have so far, how can I allow periods in this?

        What about "preg_replace(" ", "_", $filename);". Wouldn't that work? What's with all the complicated regex?!?!

          you could even skip the regex engine on that and use
          $string = str_replace(' ', '', $string);

          only reason i used it was since the \s covers all whitespace, but i just wasnt really thinking a filename cant have any other type of whitespace besides a normal space. i just started writing it was 1 regex but then split it to the two for simplicity.

            you said
            preg_replace(" ", "_", $filename);
            not
            str_replace(' ', '', $string);

              Is there much of a difference? Both functions take a string and replace it with something else...besides, mine actually does what he wants - replaces spaces with underscores 😃

                well i meant to put
                str_replace(' ', '_', $string);

                but if you dont need patterns, str_replace is much faster than preg_replace

                  Besides, preg_replace(' ', '', $filename) is missing the pattern delimiters 😃
                  Replace spaces with underscores? You mean strtr($filename,' ','
                  ');?

                    Write a Reply...