How do I remove http, https and slash from user input in php

后端 未结 10 2012
不思量自难忘°
不思量自难忘° 2020-11-29 04:30

Example user input

http://domain.com/
http://domain.com/topic/
http://domain.com/topic/cars/
http://www.domain.com/topic/questions/

I want

相关标签:
10条回答
  • 2020-11-29 04:54

    if its the first characters in the string you can use substr(0,8) , and it will remove the first 8th character if its not use the "str_replace()" function http://php.net/manual/en/function.str-replace.php

    0 讨论(0)
  • 2020-11-29 04:55

    You should use an array of "disallowed" terms and use strpos and str_replace to dynamically remove them from the passed-in URL:

    function remove_http($url) {
       $disallowed = array('http://', 'https://');
       foreach($disallowed as $d) {
          if(strpos($url, $d) === 0) {
             return str_replace($d, '', $url);
          }
       }
       return $url;
    }
    
    0 讨论(0)
  • 2020-11-29 04:55

    Create an array:

    $remove = array("http://","https://");

    and replace with empty string:

    str_replace($remove,"",$url);

    it would look something like this:

    function removeProtocol($url){
        $remove = array("http://","https://");
        return str_replace($remove,"",$url);
    }
    

    Str_replace will return a string if your haystack (input) is a string and you replace your needle(s) in the array with a string. It's nice so you can avoid all the extra looping.

    Happy Coding!

    0 讨论(0)
  • 2020-11-29 04:55

    You could use the parse url Functionality of PHP. This will work for all Protocols, even ftp:// or https://

    Eiter get the Protocol Component and substr it from the Url, or just concatenate the other Parts back together ...

    http://php.net/manual/de/function.parse-url.php

    0 讨论(0)
  • 2020-11-29 04:57

    You can remove both https and http in one line using ereg_replace:

    $url = ereg_replace("(https?)://", "", $url);
    
    0 讨论(0)
  • 2020-11-29 04:58

    Found this http://refactormycode.com/codes/598-remove-http-from-url-string

    function remove_http($url = '')
    {
        if ($url == 'http://' OR $url == 'https://')
        {
            return $url;
        }
        $matches = substr($url, 0, 7);
        if ($matches=='http://') 
        {
            $url = substr($url, 7);     
        }
        else
        {
            $matches = substr($url, 0, 8);
            if ($matches=='https://') 
            $url = substr($url, 8);
        }
        return $url;
    }
    
    0 讨论(0)
提交回复
热议问题