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 match a space using PHP regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match an exact string?
- How to use named capture groups in PHP regex?
- How to use PHP regex to match a year?
- How to match a double quote in PHP regex?
- How to use PHP regex to match URL path?
- How to convert a PHP regex to JavaScript regex?
- How to get the first match when using regex in PHP?
- How to remove all non-numeric characters using PHP regex?
See more codes...