How to check if the variable has "http: //", and if not, add it?

Basically, I use gethostbyname()to get the IP address of the specified URL, using parse_url()to determine a specific domain. However, this does not work if http://missing from the URL (if I miss the option)

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

Or, if you have a better alternative, I would like to hear it. Thank.

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

?>
+7
source

, , https , , ftp mailto , . , ":" -, , , , , , , .

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

?>

..

+1

A simple solution:

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

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

-4
source

Source: https://habr.com/ru/post/1750933/


All Articles