if http:// is in string then leave it, else if not add it

后端 未结 8 2085
执念已碎
执念已碎 2020-12-22 12:07

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 beginn

相关标签:
8条回答
  • 2020-12-22 13:10

    you forgot to return $domain.

    $domain = $_POST["domain"];
    
    if (strpos($domain, "http://") !== false) {
    return $domain;
    } else {
    return "http://" . $domain;
    }
    
    0 讨论(0)
  • 2020-12-22 13:10

    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.

    0 讨论(0)
提交回复
热议问题