How can regular expressions be used to validate URLs in PHP?

Regular expressions can be used to validate URLs in PHP by defining a pattern that matches a valid URL format. This pattern can include rules for the protocol (http, https), domain name, and path. By using the preg_match function in PHP, we can check if a given URL string matches the defined pattern, thus validating the URL.

$url = "http://www.example.com";

if (preg_match('/^(https?:\/\/)?([a-z0-9-]+\.)+[a-z]{2,6}([\/\w\.-]*)*\/?$/', $url)) {
    echo "Valid URL";
} else {
    echo "Invalid URL";
}