Add http:// prefix to URL when missing

前端 未结 10 1196
谎友^
谎友^ 2020-11-30 06:41

Hello I have a very simple code


    
Website
相关标签:
10条回答
  • 2020-11-30 07:12

    A simple solution which may not work in all cases (i.e. 'https://'):

    if (strpos($aProfileInfo['Website'],'http://') === false){
        $aProfileInfo['Website'] = 'http://'.$aProfileInfo['Website'];
    }
    
    0 讨论(0)
  • 2020-11-30 07:12

    You can use this function as a general if nothing from the array is found in the string append something to it.

    function httpify($link, $append = 'http://', $allowed = array('http://', 'https://')){
    
      $found = false;
      foreach($allowed as $protocol)
        if(strpos($link, $protocol) !== 0)
          $found = true;
    
      if($found)
        return $link;
      return $append.$link;
    }
    
    0 讨论(0)
  • 2020-11-30 07:18

    I think you'd better use the built in function parse_url() which returns an associative array with its components

    something like this will work for you:

     if  ( $ret = parse_url($url) ) {
    
          if ( !isset($ret["scheme"]) )
           {
           $url = "http://{$url}";
           }
    }
    
    0 讨论(0)
  • 2020-11-30 07:18

    You could use strpos:

    // Trim trailing whitespace
    $aProfileInfo['Website'] = trim($aProfileInfo['Website']);
    
    // Test if the string begins with "http://"
    if (strpos($aProfileInfo['Website'], 'http://') !== 0) {
      $aProfileInfo['Website'] = 'http://' . $aProfileInfo['Website'];
    }
    
    0 讨论(0)
提交回复
热议问题