How do I strip non alphanumeric characters from a string and keep spaces?

TheExit picture TheExit · May 24, 2011 · Viewed 64k times · Source

I want to create a regex that removes all non-alphanumber characters but keeps spaces. This is to clean search input before it hits the db. Here's what I have so far:

@search_query = @search_query.gsub(/[^0-9a-z]/i, '')

Problem here is it removes all the spaces. Solutions on how to retain spaces?

Answer

jwueller picture jwueller · May 24, 2011

Add spaces to the negated character group:

@search_query = @search_query.gsub(/[^0-9a-z ]/i, '')