1

I am attempting to have a input field for adding a website/url. All I want to require to successfully submit the form is www.domainname.com; however, after submission I want to add back on http:// or https:// if it was not added by the person submitting the form.

The validation is along the lines of the following,

public function name($id) {

$input = Input::all();
$validator = Validator::make(
  $input,
  array(
    'website' => 'active_url',
  )
);

}

For this to work an if statement is needed. I have tried inserting something along the lines of the code listed below, but have not had any luck.

if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
  $url = "http://" . $url;
}

I am fairly new to PHP and just starting to use Laravel, so I apologize in advance if there is any confusion or lack of information. Any help is appreciated.

3 Answers 3

1

You could simply just strip the scheme to begin with and then add it.

$url = preg_replace('#^https?://#', '', $url);
$url = "http://" . $url;

Or

$url = ltrim('http://', $url);
$url = ltrim('https://', $url);
$url = 'http://' . $url;

Or

if (!preg_match('#^http(s)?://#', $url)) {
  $url = 'http://' . $url;
}
Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

if (stripos($url, "http://") === false && stripos($url, "https://") === false) {
  $url = "http://" . $url;
}

stripos is case-insensitive, so it shouldn't matter if the user typed in lowercase letters or not in the url prefix.

Comments

0

I think no need for validation,.. maybe it could help you

@alix axel code

function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.