Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

Replace non word characters EXCEPT hyphen



4:34 pm on Dec 16, 2010 (gmt 0)

5+ Year Member

I'm trying to allow the use of the hyphen (dash) in a text input, but I can't get it to work. I've tried the following with no success:

$string =~ s/[^\w|-]//g;
$string =~ s/[^\w\-]//g;
$string =~ s/[^a-zA-Z0-9-]//g;

I've also tried the ascii code - with and without escaping the & and ;

Any help would be greatly appreciated!


11:36 pm on Dec 16, 2010 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member

\w is a char-group itself, so depending on the locale you are working with, it's something like [-a-zA-Z]

the hyphen is a special char in groups, and you'll have to escape it, unless it's the first char, so

$string =~ s/[^a-zA-Z0-9-]//g;

should be
$string =~ s/[^a-zA-Z0-9\-]//g;


4:56 pm on Dec 17, 2010 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

Right, unless escaped the hyphen represents a range. The above is equivalent to

$string =~ s/[^a-z\d\-]//ig;

with the i modifier (case insensitive) and \d, which is any digit. :-)


5:25 pm on Dec 17, 2010 (gmt 0)

5+ Year Member

Thanks both of you! I appreciate it. I thought it (the hyphen) needed to be escaped, but that wouldn't work either until I found another spot in the code about 1000 lines down that was preventing it from working. I have it working now. Thanks also for the shortcut example!

Featured Threads

Hot Threads This Week

Hot Threads This Month