Regex to replace unsafe chars?

B

Bryan Coon

I need to remove unsafe characters from a filename, and replace them all
with underscores.

The characters I need to search for and replace are:
!@#$%^*()'"{}[]<>

How do I search and replace for any of the group of special characters
like this?

I tried $filename =~ s/[\!\@\#\$\%\^\*\(\)\{\}\[\]\'\"\<\>]/_/g;
But I dont think they all need to be escaped and Im not sure this is the
right format anyways.

Thanks,
B
 
J

Jaap Karssenberg

I need to remove unsafe characters from a filename, and replace them
: all with underscores.

maybe it would be better to define the save characters, say a filename
should only contain letters, digits, '.' and '-' then you could do this:

$filename =~ s/[^\w\.\-]/_/g;
 
A

A. Sinan Unur

I need to remove unsafe characters from a filename, and replace them
all with underscores.

You should decide what is safe and only allow those characters instead of
trying to figure out what is not safe.

Sinan.
 
B

Bob Walton

Bryan said:
I need to remove unsafe characters from a filename, and replace them all
with underscores.

The characters I need to search for and replace are:
!@#$%^*()'"{}[]<>

How do I search and replace for any of the group of special characters
like this?

I tried $filename =~ s/[\!\@\#\$\%\^\*\(\)\{\}\[\]\'\"\<\>]/_/g;
But I dont think they all need to be escaped and Im not sure this is the
right format anyways. ....
B

This is probably best done with the translate operator [untested]:

$filename=~tr/!@#$%^*()'"{}[]<>/_/;
 
J

James Willmore

I need to remove unsafe characters from a filename, and replace them
: all with underscores.

maybe it would be better to define the save characters, say a filename
should only contain letters, digits, '.' and '-' then you could do this:

$filename =~ s/[^\w\.\-]/_/g;

I'll go one better and direct the OP to a CERT page on exactly this idea -
as applied to untainting variables in CGI scripts ....

http://www.cert.org/tech_tips/cgi_metacharacters.html

HTH

--
Jim

Copyright notice: all code written by the author in this post is
released under the GPL. http://www.gnu.org/licenses/gpl.txt
for more information.

a fortune quote ...
Elevators smell different to midgets
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top