Validating URL in PHP with filter function and reguler expression

While taking URL as user input, it's essential to validate it properly otherwise it can effect application. In this article, we will validate URLs in PHP with regular expressions and also with FILTER_VALIDATE_URL function. You can implement those methods in other PHP based frameworks like Laravel or CI.

Here, we will see two methods. Both checks URL is valid or not using PHP functionality.

  1. Validate URL Using Regex
  2. Validate URL Using Filter (FILTER_VALIDATE_URL)

The preg_match() regular expression is aimed to search pattern into string. It will return True if match found otherwise, false. While in other method, we will use filter function. This function is used to filter variable's value by per-defined filters. Here, we will use URL validation filter.

Validate URL Using Regex

Regex methods just work like search with some specific conditions or we can say multiple search term into one value. For this example, we will define our URL statically. You can take URL as user input as per your requirement.

Validate URL Using Filter

PHP provide filter_var() inbuilt function with FILTER_VALIDATE_URL filter. Here, we just have to pass URL and it will automatically validate and return status. There are few flags like FILTER_FLAG_HOST_REQUIRED or FILTER_FLAG_PATH_REQUIRED which you can use as per your requirements.


In this article, we have validated URL using filter function and regular expression. The filter method is idle for this purpose because of flag and it's easy to implement.

Share your thoughts

Ask anything about this examples