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 use PHP regex to match a zip code?
- How to use PHP regex to match special characters?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match a boolean value?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match a hashtag?
- How to use PHP regex to match an XML tag?
- How to match a single quote in PHP regex?
See more codes...