Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

ereg_replace is now deprecated, so it is better to use:

$url = preg_replace("(^https?://)", "", $url );

This removes either http:// or https://


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;
}

I'd suggest using the tools PHP gave you, have a look at parse_url.

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>

The above example will output:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path

It sounds like you're after at least host + path (add others as needed, e.g. query):

$parsed = parse_url('http://www.domain.com/topic/questions/');

echo $parsed['host'], $parsed['path'];

    > www.domain.com/topic/questions/

Cheers


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.


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

$url = ereg_replace("(https?)://", "", $url);