php-regexHow to use PHP regex to match URL?
Using PHP regex to match URL is a powerful way to validate and parse URLs. The following example code block shows how to use regex to match a URL:
$url = 'http://www.example.com/path/to/page.html';
$pattern = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';
if(preg_match($pattern, $url)) {
echo 'The URL is valid';
} else {
echo 'The URL is not valid';
}
The output of the example code is:
The URL is valid
Code explanation
$url
: a string containing the URL to be matched$pattern
: a regex pattern to match the URLpreg_match()
: a PHP function to match a regex pattern against a string
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a multiline?
- How to match a quotation mark in PHP regex?
- How to get last matched occurrence in PHP regex?
- How to match a single quote in PHP regex?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match special characters?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match a year?
- How to match a space using PHP regex?
See more codes...