【问题标题】:php return request URI from stringphp从字符串返回请求URI
【发布时间】:2014-03-12 17:09:32
【问题描述】:

我有一个场景,用户可以在文本字段中输入网址,我需要从中返回 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

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

【问题讨论】:

    标签: php regex url uri parse-url


    【解决方案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";
    }
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • @andrewtweber 谢谢!我的服务器仍然运行 5.4.24 ;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      相关资源
      最近更新 更多