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

后端 未结 8 2074
执念已碎
执念已碎 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 12:53

    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;
    }
    
    0 讨论(0)
  • 2020-12-22 12:56

    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){
    
    0 讨论(0)
  • 2020-12-22 12:58
    if (strpos($domain, "http://") !== false) {
    //return substr($domain,7); Thanks Rocket. 
    return $domain;
    } else {
    return "http://" . $domain;
    }
    
    0 讨论(0)
  • 2020-12-22 13:02

    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.

    0 讨论(0)
  • 2020-12-22 13:03

    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.

    0 讨论(0)
  • 2020-12-22 13:05

    "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 );
    
    0 讨论(0)
提交回复
热议问题