I'm making a search form, so I want the user to enter any word or string which contains alpha numeric and space between the words.
I want to allow alpha numeric and spaces in the search bar but so far I'm not successful. I did research on google to find something that can help me to do this but so far no luck. I need your help on how to write the regular expression for preg_match
So what i am trying to do here is replace any character that is not 0-9 a-z A-Z and space be replaced with ""
$searchq = mysql_prep(urldecode($_GET['q']));
$searchq = preg_replace("#[^0-9a-z\s+]#i", "", $searchq);
EDIT: After getting deep into what is happening and what i want to achieve, i found out that the problem is with my query and not my regex ! If the user enters for example first name and last name eg John Doe, i want the search result to get back with John doe from database ! so I need please your help with my query on how can i make this achievable, i have 2 columns one for First name which is "first_name" and one for last name which is "last_name"
here is my query :
$query_search2 = "SELECT * FROM users_table WHERE first_name LIKE '%$searchq%' OR last_name LIKE '%$searchq%' OR username LIKE '%$searchq%' OR first_name LIKE '%$searchq%' AND last_name LIKE '%$searchq%'";
You can use the following Regex, which will find All alphabets regardless of case. A-Z, a-z, 0-9, white spaces which includes tabs, and underscore.
Regex: '(?:\w+|\s+){1,}'
If you do not want to capture Underscore, you can use the following:
Regex: '([A-Za-z0-9]+|\s+){1,}'
The solution i managed to find is this : for regex expression i used :
$searchq = preg_replace("/[^A-Za-z0-9\s ]/", "", $searchq);
and for the query i used this :
// ut is the designation of the users_table which we define ourselves
$query_search2 = "SELECT * FROM users_table ut WHERE CONCAT(ut.first_name, ' ', ut.last_name) LIKE '%$searchq%'";
You need to update the query as follows. Your Regex here text needs to be replaced with the regex you want to use. I hope this helps, if not please revert back with your problem.
SELECT * FROM USER_TABLE WHERE REGEXP_LIKE (first_name, 'your regex here') OR REGEXP_LIKE (last_name, 'your regex here') OR REGEXP_LIKE (username, 'your regex here'); If you are using your variable of regex in the query then print the query and make sure the query is getting generated correctly.
Use regex as per your need.--> You can use the following Regex, which will find All alphabets regardless of case. A-Z, a-z, 0-9, white spaces which includes tabs, and underscore.
Regex: '(?:\w+|\s+){1,}'
If you do not want to capture Underscore, you can use the following:
Regex: '([A-Za-z0-9]+|\s+){1,}