The task is to find if the string starts with http:// or https:// or ftp://
$regex = "((https?|ftp)://)?";
but preg_match($regex) does not work correctly. What should I change?
You need to use a delimiter (/) around the RegExp :)
// Protocol's optional
$regex = "/^((https?|ftp)\:\/\/)?/";
// protocol's required
$regex = "/^(https?|ftp)\:\/\//";
if (preg_match($regex, 'http://www.google.com')) {
// ...
}
http://br.php.net/manual/en/function.preg-match.php
Is it necessary to use regex? One could achieve the same thing using string functions:
if (strpos($url, 'http://') === 0 ||
strpos($url, 'https://') === 0 ||
strpos($url, 'ftp://') === 0)
{
// do magic
}
You need: preg_match ('#((https?|ftp)://)?#', $url)
The # delimiters remove the need to escape /, which is more convenient for URLs
Like this:
$search_for = array('http', 'https', 'ftp');
$scheme = parse_url($url, PHP_URL_SCHEME);
if (in_array($scheme, $search_for)) {
// etc.
}
Related
I have a form to accept URL inputs.
I want the URL in following format whatever format the input may be in.
https://www.example.com
So if anyone enters below links I want to convert them to above format
example.com
http://example.com
https://example.com
http://www.example.com
If they input in correct format no need to change the URL.
Below is what I tried but could not succeed.
//append https:// and www to URL if not present
if (!preg_match("~^(?:f|ht)tps?://~i", $url0) OR strpos($url0, "www") == false) {
if ((strpos($url0, "http://") == false) OR (strpos($url0, "https://") == false) AND strpos($url0, "www") == false ){
$url0 = "https://www." . $url0;
}
else if (strpos($url0, "www") != false ){
}
else {
$url0 = "https://" . $url0;
}
}
You can try a regex like this
$str = preg_replace('~^(?:\w+://)?(?:www\.)?~', "https://www.", $str);
It will replace any protocol and/or www. with https://www. or add if none is present.
^ matches start of the string, (?: starts a non capture group.
(?:\w+://)? optional protocol (\w+ matches one or more word characters [A-Za-z0-9_])
(?:www\.)? optional literal www.
See demo and more explanation at regex101
You can use the parse_url function to check out the formatting of the URL:
<?php
$url = parse_url($url0);
// When https is not set, enforce it
if (!array_key_exists('scheme', $url) || $url['scheme'] !== 'https') {
$scheme = 'https';
} else {
$scheme = $url['scheme'];
}
// When www. prefix is not set, enforce it
if (substr($url['host'], 0, 4) !== 'www.') {
$host = 'www.' . $url['host'];
} else {
$host = $url['host'];
}
// Then set/echo this in your desired format
echo sprintf('%s://%s', $scheme, $host);
This should save you (and anyone having to work on this script in the future) some regex headaches and also keeps the code more readable.
So I need a regex that I can use in preg_replace that'll tell me if $string starts with http:// (or https) i.imgur.com/
Any help? I'm not that good with regex heh
so far what I have:
<?php
$url = "httPs";
if (preg_match('#^http#i', $url) === 1) {
// Starts with http (case insensitive).
die('ye');
}
else
{die('nop');}
?>
Try /\/\/i\.imgur\.com/
Does that make sense? The double slash after http(s) allows the pattern to only check at the beginning of the domain of the url
So
if (preg_match('\/\/i\.imgur\.com', $url)) { ...
<?php
$url = 'https://i.imgur.com/image';
if (preg_match('/^https?\:\/\/i\.imgur\.com\//', $url)) {
die('yes');
} else {
die('no');
}
I have a input that you enter a URL, i basically want to write some php that says if the domain containts "http://" then leave it be, else if not then add it to the beginning.
This is what I have so far...
$domain = $_POST["domain"];
if (strpos($domain, "http://")) {
return $domain;
} else {
$domain = "http://" . $domain;
}
This doesnt seem to work..
it doesnt add the http:// on if it doesnt contain http://.
you forgot to return $domain.
$domain = $_POST["domain"];
if (strpos($domain, "http://") !== false) {
return $domain;
} else {
return "http://" . $domain;
}
Since the string starts with http://, strpos will return 0, which will evaluate to false.
Change the if statement to:
if(strpos($domain, "http://") !== FALSE){
"http://" then leave it be, else if not then add it to the beginning.
How about adding adding it regardless? I find that to be easier:
<?php
$url = 'http://www.google.com';
echo 'http://' . preg_replace( '~^http://~', '', $url );
read manual:
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator for
testing the return value of this
function.
That is because strpos will return the location of the string, within the string.
In your url, that is 0. Which equals to false. Make it a strict check - add === false.
if (strpos($domain, "http://") !== false) {
//return substr($domain,7); Thanks Rocket.
return $domain;
} else {
return "http://" . $domain;
}
I know this is a bit late to the party, but I prefer this approach:
if (!preg_match('#^http[s]{0,1}://#', $input)) {
$input = 'http://' . $input;
}
This will preserve a https:// address, and not have you ending up with http://https://www.mysite.com. You could also further edit it to strip out https:// if you had a rule for not using https addresses.
I know the original question didn't ask for this, but I think it's important to consider in most situations, and will hopefully help someone else who comes looking.
Use caution when using strpos(). It will return 0 when 'http://' is found at the beginning of the string, causing your if statement to fail unexpectedly. You will want to check the type of the return to be sure:
$domain = $_POST["domain"];
if (FALSE !== strpos($domain, "http://")) {
return $domain;
} else {
return "http://" . $domain;
}
So here is what I need to do.
If an user enters this: http://site.com I need to remove http:// so the string will be site.com , if an user enters http://www.site.com I need to remove http://www. or if the user enters www.site.com I need to remove www. or he can also enter site.com it will be good as well.
I have a function here, but doesn't work how I want to, and I suck at regex.
preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $_POST['link'])
Use filter_var() instead.
if (filter_var($_POST['link'], FILTER_VALIDATE_URL)) {
// valid URL
} else {
// not valid
}
There is also parse_url function.
I don't think I'd use regex for this, since you're only really checking for what is at the beginning of the string. So:
$link = $_POST['link'];
if (stripos($link, 'http://') === 0)
{
$link = substr($link, 7);
}
elseif (stripos($link, 'https://') === 0)
{
$link = substr($link, 8);
}
if (stripos($link, 'www.') === 0)
{
$link = substr($link, 4);
}
should take care of it.
i always go with str_replace haha
str_replace('http://','',str_replace('www.','',$url))
I think what you're looking for is a multi-stage preg_replace():
$tmp = strtolower($_POST['link']) ;
$tmp = preg_replace('/^http(s)?/', '', $tmp);
$domain = preg_replace('/^www./', '', $tmp) ;
This simplifies the required regex quite a bit too.
How can I add http:// to a URL if it doesn't already include a protocol (e.g. http://, https:// or ftp://)?
Example:
addhttp("google.com"); // http://google.com
addhttp("www.google.com"); // http://www.google.com
addhttp("google.com"); // http://google.com
addhttp("ftp://google.com"); // ftp://google.com
addhttp("https://google.com"); // https://google.com
addhttp("http://google.com"); // http://google.com
addhttp("rubbish"); // http://rubbish
A modified version of #nickf code:
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
Recognizes ftp://, ftps://, http:// and https:// in a case insensitive way.
At the time of writing, none of the answers used a built-in function for this:
function addScheme($url, $scheme = 'http://')
{
return parse_url($url, PHP_URL_SCHEME) === null ?
$scheme . $url : $url;
}
echo addScheme('google.com'); // "http://google.com"
echo addScheme('https://google.com'); // "https://google.com"
See also: parse_url()
Simply check if there is a protocol (delineated by "://") and add "http://" if there isn't.
if (false === strpos($url, '://')) {
$url = 'http://' . $url;
}
Note: This may be a simple and straightforward solution, but Jack's answer using parse_url is almost as simple and much more robust. You should probably use that one.
The best answer for this would be something like this:
function addhttp($url, $scheme="http://" )
{
return $url = empty(parse_url($url)['scheme']) ? $scheme . ltrim($url, '/') : $url;
}
The protocol flexible, so the same function can be used with ftp, https, etc.
Scan the string for ://. If it does not have it, prepend http:// to the string... Everything else just use the string as is.
This will work unless you have a rubbish input string.
Try this. It is not watertight1, but it might be good enough:
function addhttp($url) {
if (!preg_match("#^[hf]tt?ps?://#", $url)) {
$url = "http://" . $url;
}
return $url;
}
1. That is, prefixes like "fttps://" are treated as valid.
nickf's solution modified:
function addhttp($url) {
if (!preg_match("#^https?://#i", $url) && !preg_match("#^ftps?://#i", $url)) {
$url = "http://" . $url;
}
return $url;
}
<?php
if (!preg_match("/^(http|ftp):/", $_POST['url'])) {
$_POST['url'] = 'http://'.$_POST['url'];
}
$url = $_POST['url'];
?>
This code will add http:// to the URL if it’s not there.