如何在PHP中获取URL的最后两部分?

问题描述:

I have this URL: http://itutormaths.hub/home/hub/6/hello/world and I want grab only hello and world.

How would I do this?

Thanks!

<?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);

$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);

use explode function

<?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 />";

?>

Or check out preg_mactch_all (php.net/manual/en/function.preg-match-all.php)