Home / Programming / Perl / I need to get rid of all non-alphanumeric characters from a string - how can I do it?
I need to get rid of all non-alphanumeric characters from a string - how can I do it?
Last updated: 06/30/2009
In Perl, a simple regular expression will handle this. Here's an example:
$var = "This string has some ' bogus ( characters. 922"; $var =~ s/\W/_/g; print $var;
The output of this would be:
This_string_has_some___bogus___characters__922
This is useful if you are creating a file, and need the name to be friendly to the filesystem. Or if you are creating a string for a hash, or something where odd characters just present some extra headaches.