php-regexHow to use PHP regex to match http or https?
The following example code uses PHP regex to match http or https:
$url = "https://www.example.com";
if (preg_match("/^(http|https):\/\/.*/", $url)) {
echo "URL matches http or https";
}
Output example
URL matches http or https
Code explanation
$url = "https://www.example.com";- This line assigns the value of the URL to the variable$url.if (preg_match("/^(http|https):\/\/.*/", $url)) {- This line uses thepreg_match()function to check if the URL matches the regular expression/^(http|https):\/\/.*/. The^character indicates the start of the string, the(http|https)part matches eitherhttporhttps, the:\/\/part matches the://part of the URL, and the.*part matches any character (including none) until the end of the string.echo "URL matches http or https";- This line prints out the messageURL matches http or httpsif the URL matches the regular expression.
Helpful links
More of Php Regex
- How to use PHP regex to match an exact string?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match a zip code?
- How to match a single quote in PHP regex?
- How to match a double quote in PHP regex?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to match a quotation mark in PHP regex?
- How to use regex in PHP to match any character including newline?
- How to use PHP regex with the "x" modifier?
See more codes...