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

时间:2012-03-15 17:19:42

标签: php string url search

我有这个网址:http://itutormaths.hub/home/hub/6/hello/world我只想抓住你好和世界。

我该怎么做?

谢谢!

3 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:0)

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

使用爆炸功能

答案 2 :(得分:0)

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