in reply to Removing Bad Characters from a String

The concept of 'bad' characters should be avoided.

If you have reason to believe that there are characters that may cause problems, you will do better to make sure that you only keep characters that you know to be good. This keeps you from accidentally letting through characters that you hadn't thought of.

It doesn't need to be a subroutine (as it's a whole one line), but you can do it so you're consistent between various points in the program (or cross program, depending on how you handle it.)

There are three ways to handle this normally -- removal, replacement, and reversable:

sub remove { my $string = shift; $string =~ s/[^a-zA-Z0-9.\-_]//g; return $string; } sub replace { my $string = shift; $string =~ s/[^a-zA-Z0-9.\-_]/_/g; return $string; } sub reversable { my $string = shift; $string =~ s/([^a-zA-Z0-9.\-_])/sprintf('=%x',unpack('C',$1))/eg; return $string; }

Replies are listed 'Best First'.
Re^2: Removing Bad Characters from a String
by kennedymr2 (Initiate) on May 09, 2005 at 22:12 UTC
    Appreciate the help offered by all the members of this forum. This is the 1st time i have used this forum, and am very impressed with the reponse to my question. The server i am using is unix I have done some more testing, and the main character i seem to have a problem with is \ or /, where it seems to indicate a change in directory in the output file name I will use this the code offered by jhourcle to get around the problem. Also , thanks to all the other members who have given advice. Once again, really appreciate the help regards ,kennedymr2