【问题标题】:How do I grab the last two parts of an URL in PHP?如何在 PHP 中获取 URL 的最后两部分?
【发布时间】:2012-03-15 17:19:42
【问题描述】:

我有这个 URL:http://itutormaths.hub/home/hub/6/hello/world,我只想获取 hello 和 world。

我该怎么做?

谢谢!

【问题讨论】:

标签: php string url search


【解决方案1】:
<?php

$url = 'http://itutormaths.hub/home/hub/6/hello/world';

$pathParts = explode( '/', parse_url($url, PHP_URL_PATH) );

$lastParts = array( array_pop($pathParts), array_pop($pathParts) );

var_dump($lastParts);

【讨论】:

    【解决方案2】:
    <?php
    //returns all occurrences of a string
    function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {                
        $offset = strpos($haystack, $needle, $offset);
        if($offset === false) {
            return $results;            
        } else {
            $results[] = $offset;
            return strpos_recursive($haystack, $needle, ($offset + 1), $results);
        }
    }
    
    $url = "http://itutormaths.hub/home/hub/6/hello/world";
    
    $positions = strpos_recursive($url,"/");
    
    
    
    //World (ie the 7th occurence of /)
    echo substr($url, $positions[6]+1)."<br />";
    
    //hello (ie the string between the 6th and 7th occurence of /)
    echo substr($url, $positions[5]+1,($positions[6]-$positions[5]-1))."<br />";
    
    ?>
    

    或查看 preg_mactch_all (php.net/manual/en/function.preg-match-all.php)

    【讨论】:

      【解决方案3】:
      $url='http://itutormaths.hub/home/hub/6/hello/world';    
      $res=explode("6/",$url);    
      $res1=$res[1];    
      
      $res=explode("/",$res1);
      $res1=$res[0];
      print_r($res1);
      $res2=$res[1];
      print_r($res2);
      

      使用爆炸功能

      【讨论】:

        猜你喜欢
        • 2011-11-15
        • 2013-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-14
        • 2011-10-22
        相关资源
        最近更新 更多