1

我有一个场景,用户可以在文本字段中输入网址,我需要从中返回 URI。

因此,用户可能会以以下完整状态输入地址-

http://www.google.co.uk/contoller/function?stuff=thing
www.google.co.uk/controller/function?stuff=thing
google.co.uk/controller/function?stuff=thing
/controller/function?stuff=thing
controller/function?stuff=thing

从所有这些示例中,我需要返回:

/controller/function?stuff=thing

(请注意,域名可以是任何东西,而不仅仅是谷歌!)

4

2 回答 2

1

您可以为此目的使用 PHP parse_url(),但这需要 URI 的格式正确。

$parsed = parse_url($url);
var_dump( $parsed['path'] . $parsed['query'] );

只要 URI 以开头,就会得到正确的结果http://(否则域也将被解析为路径)。

于 2014-03-12T17:10:27.987 回答
1
$arr = array(
    'http://www.google.co.uk/contoller/function?stuff=thing',
    'www.google.co.uk/controller/function?stuff=thing',
    'google.co.uk/controller/function?stuff=thing',
    '/controller/function?stuff=thing',
    'controller/function?stuff=thing',
);

foreach($arr as $a){
    print "/".preg_replace("@https?://.*?(/|$)|[^\s/]+\.[^\s/]+/|^/@", "", $a) . "\n";
}
于 2014-03-12T17:21:37.913 回答