如何检查变量中是否包含“http://”,如果不是,请添加它?

Basically, I'm using gethostbyname() to get the IP address of the specified URL, using parse_url() to determine the specific domain. However, this doesn't work if http:// is not in the URL (unless I'm missing an option)

So how can I check if http:// is in the URL, and if not, add it appropriately?

Or if have a better alternative, I'd like to hear it. Thanks.

<?php
  $url = [some url here];
  if(substr($url, 0, 7) != 'http://') {
     $url = 'http://' . $url;
  }

?>

if (strpos("http://", $url) === "true"){ action };

Hmm, strictly speaking, you need to consider https as well, and maybe even ftp and mailto depending on what you are doing. You might want to check for a ':' first, without one you DEFINITELY don't have a protocol, and could skip the rest, with one you might have a protocol, or maybe a port specification.

  <?php 
  $url = [some url here]; 
  if(substr($url, 0, 7) != 'http://') { 
      if(substr($url, 0, 8) != 'https://') { 
         $url = 'http://' . $url; 
      } 
  } 

?>

etc

Simple solution:

if(!preg_match('/http[s]?:\/\//', $url, $matches)) $url = 'http://'.$url;