Is there a built-in php (or MySQL) function that will sanitise a string to be used in a search? In this case, I want to make a string alphabet (upper and lower) only, before it’s passed into a MySQL regex.
I’m using PDO and parameterized queries, so I’m not worried about SQL injection. However, I want to make sure someone doesn’t pass in wildcards and use up too much memory. So far, this is what I’m using to remove everything but spaces and the alphabet. Is this enough?
preg_replace("/[^A-Za-z\s\s+]/", "", $query);
The regular expression you have will strip more than just the wildcards you are worried about, so I don’t think it’s the best solution. (You’ve undoubtedly heard this quote, but I’ll repeat it anyhow.)
There are built-in PHP functions that can help you with filtering. Take a look at using filter_var() in combination with PHP’s sanitize filters, if you want to do something like sanitize a URL or e-mail.
However, in your case, I think the following is simplest.