2010-12-05 180 views
25

实例用户输入如何删除HTTP,HTTPS和来自用户的输入削减在PHP

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

我想一个PHP函数来作出这样

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

输出让我知道:)

+0

用`c.om`应该是`.com`的错字。我无法建议编辑,因为系统显示“编辑必须至少包含6个字符;” ... – 2014-05-05 13:42:02

回答

22

你应该使用 “禁止” 条款的数组,并使用strposstr_replace从传入的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

很酷..如果有没有斜杠sub.domain.com? – Blur 2010-12-05 06:35:03

+0

@blur如果字符串不包含任何“禁止”字符串,这将优雅地返回。 – 2010-12-05 06:37:24

+1

如果URL类似于:`http://domain.com/topic/https:// more /`?这是一个有效的路径,但是这种方法会以一种(我认为)OP不会打算的方式来破坏它。 – Lee 2010-12-05 06:51:05

-2

发现这个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; 
} 
-1

你可以使用PHP的解析url功能。这将会对所有协议的工作,甚至是FTP://或https://

Eiter获得协议组件并从URL SUBSTR,或者只是串联的其他部分一起回来......

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

2

您可以删除HTTPS和使用一个行HTTP ereg_replace:

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

ereg_replace现在已经过时,所以最好使用:

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

这消除或者http://https://

18

我使用PHP给你的工具提示,看看parse_url

<?php 
$url = 'http://username:[email protected]/path?arg=value#anchor'; 

print_r(parse_url($url)); 

echo parse_url($url, PHP_URL_PATH); 
?> 

上面的例子将输出:

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

这听起来像你后至少host + path(根据需要添加其他,如query):

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

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

    > www.domain.com/topic/questions/ 

干杯

-1

我刚刚有同样的问题一点点b它之前,但这真的是最好的:

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

非常干净,高效。

-1
<?php 
// user input 
$url = 'http://www.example.com/category/website/wordpress/wordpress-security/'; 
$url0 = 'http://www.example.com/'; 
$url1 = 'http://www.example.com/category/'; 
$url2 = 'http://www.example.com/category/website/'; 
$url3 = 'http://www.example.com/category/website/wordpress/'; 

// print_r(parse_url($url)); 
// echo parse_url($url, PHP_URL_PATH); 

$removeprotocols = array('http://', 'https://'); 

echo '<br>' . str_replace($removeprotocols,"",$url0); 
echo '<br>' . str_replace($removeprotocols,"",$url1); 
echo '<br>' . str_replace($removeprotocols,"",$url2); 
echo '<br>' . str_replace($removeprotocols,"",$url3); 

?>