Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a url with lots of querystrings

I have an auto site and I am having a feature called SAVE SEARCH, which saves the search a user has made on the site for future use. What I am doing is that I am saving entire url in the database.

But I need to validate it as a valid url. It looks like this.

http://www.anywebsite.com/cars.php?postcode=CV2+5AS&distance=&make=&min_price=&max_price=&category_type=&body_type=&fuel=&colour=&transmission=&year_of_registration=&mileage=&engine=&doors=&seller=&keywords=&sort=PRICE_LOWEST&referer_url=http%253A%252F%252Flocalhost%252Fselling%252Fcars.php&trader_id=0&case=ADVANCE

Can anyone please provide me with any idea as to how I can achieve it?

I have preg_match which is here.

if (!preg_match('/^https?:(\/\/)?(www\.)?([a-zA-Z0-9_%]*)\b\.[a-z]{2,4}(\.[a-z]{2})?/', $fields[$field_name]))

But it only validates urls such as http://www.anywebsite.com, whereas I need to validate the entire above url.

Any help will be highly appreciated.

like image 452
Asnexplore Avatar asked Jan 25 '26 22:01

Asnexplore


1 Answers

You should use filter_vars() with FILTER_VALIDATE_URL filter as suggested in other answers. However, if you want to use RegEx, you must see In search of the perfect URL validation regex blog by @Mathias Bynens

I'll only add one RegEx by @diegoperini that supports all the URL patterns.

^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$

like image 164
Tushar Avatar answered Jan 27 '26 10:01

Tushar