开发者

How can I check if 'http://' is in the variable, and if not, add it?

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 开发者_StackOverflow中文版(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;
  }

?>


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;


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜