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?
Using Regular Expression We can use the regular expression [^a-zA-Z0-9] to identify non-alphanumeric characters in a string. Replace the regular expression [^a-zA-Z0-9] with [^a-zA-Z0-9 _] to allow spaces and underscore character.
Non-alphanumeric characters can be remove by using preg_replace() function. This function perform regular expression search and replace. The function preg_replace() searches for string specified by pattern and replaces pattern with replacement if found.
1. Using regular expressions. A simple solution is to use regular expressions for removing non-alphanumeric characters from a string. The idea is to use the special character \W , which matches any character which is not a word character.
Add spaces to the negated character group:
@search_query = @search_query.gsub(/[^0-9a-z ]/i, '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With