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 eitherhttp
orhttps
, 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 https
if the URL matches the regular expression.
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 special characters?
- How to use an "or" condition in PHP regex?
- How to use PHP regex to match a zip code?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match an exact string?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match whitespace?
See more codes...