如何在PHP中获取前3个部分的URL?

时间:2014-04-25 05:19:19

标签: php url

如何使用PHP获取当前URL的前3个部分。

例如:

我的网址:http://something.com/somebody/somegirls/whatever/

获取零件后的结果:http://something.com/somebody/somegirls/

这是我的代码PHP获取当前URL:

<?php   function curPageURL() {
        $url  = isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] ? 'https' : 'http';
        $url .= '://' . $_SERVER['SERVER_NAME'];
        $url .= in_array( $_SERVER['SERVER_PORT'], array('80', '443') ) ? '' : ':' . $_SERVER['SERVER_PORT'];
        $url .= $_SERVER['REQUEST_URI'];
        return $url;
    }

 $current_url = str_replace("www.", "", curPageURL());

?>

7 个答案:

答案 0 :(得分:8)

试试这个,

<?php
  $url = 'http://something.com/somebody/somegirls/whatever/';
  $parts = explode('/', $url);
  $new_url = $parts[0].'/'.$parts[1].'/'.$parts[2].'/'.$parts[3].'/'.$parts[4].'/';
  echo $new_url;
?>

<强>输出

http://something.com/somebody/somegirls/

答案 1 :(得分:5)

假设您已从您的功能中抓取此网址...

<?php
$url='http://www.something.com/somebody/somegirls/whatever/';
$parts=explode('/',parse_url($url)['path']);
array_unshift($parts,trim(strstr(parse_url($url)['host'],'.'),'.'));
print_r(array_filter($parts));

<强> OUTPUT :

Array
(
    [0] => something.com
    [2] => somebody
    [3] => somegirls
    [4] => whatever
)

Demonstration

答案 2 :(得分:2)

您还可以使用parse_url获取数组中的部分网址,如下所示:

$current_url_array = parse_url($current_url);
var_dump($current_url_array);

答案 3 :(得分:1)

您可以使用regexp:

<?php

    function getFirstUrlContents($Url) {
        preg_match_all('/^([^\/]*\/){5}/', $Url, $MatchesArray);
        return $MatchesArray[0];
    }

    var_dump(getFirstUrlContents('http://something.com/somebody/somegirls/whatever/'));

?>

答案 4 :(得分:1)

<?php
   $url='http://something.com/somebody/somegirls/whatever' ;
    $explode=explode("/", $url);
    $search=end($explode);

   echo $currentUrl=str_replace($search,'',$url);
?>

输出

http://something.com/somebody/somegirls/

答案 5 :(得分:1)

试试这个:

<?php
$url = 'http://something.com/somebody/somegirls/whatever/';
$pos = explode('/', $url);
for($i=0; $i<5; $i++){
    echo $pos[$i].'/';
}
?>

输出:http://something.com/somebody/somegirls/

答案 6 :(得分:1)

请检查以下代码。

function createUrl($array, $pos) {
    $string = '';
    for ($i = 0; $i < $pos; $i++)
    $string .=$array[$i].'/';
    return $string;
}

$current_url = "http://something.com/somebody/somegirls/xyz/yui";
$initial_string = (stripos($current_url, 'https://') !== FALSE) 
                       ? 'https://'
                       : ((strpos($a, 'http://') !== FALSE)
                       ? 'http://' : '');
$last_string = explode('/', substr($a, strlen($initial_string)));

$final_url = $initial_string.
        (count($last_string) > 3)
        ? createUrl($last_string, 3)
        : substr($current_url, strlen($initial_string));
echo $final_url;