2017-09-28 36 views

回答

1

你可以使用這個,你可以得到你需要的輸出:

// implode string into array 
$url = "http://192.168.0.16/wordpress/blog/page-2/"; 
//then remove character from right 
$url = rtrim($url, '/'); 
// then explode 
$url = explode('/', $url); 
// remove the last element and return an array 
json_encode(array_pop($url)); 
// implode again into string 
echo implode('/', $url); 

另一種方法是:

// implode string into array 
$url = explode('/', 'http://192.168.0.16/wordpress/blog/page-2/'); 
//The array_filter() function filters the values of an array using a callback function. 
$url = array_filter($url); 
// remove the last element and return an array 
array_pop($url); 
// implode again into string 
echo implode('/', $url); 
+0

輸出:http://192.168.0.16/wordpress/blog/page-2 –

+0

從url.it中刪除最後一個斜槓將工作 –

+0

你可以添加這個$ url = array_filter($ url); –

0
$url = 'http://192.168.0.16/wordpress/blog/page-2/'; 
    // trim any slashes at the end 
    $trim_url = rtrim($url,'/'); 
    // explode with slash 
    $url_array = explode('/', $trim_url); 
    // remove last element 
    array_pop($url_array); 
    // implade with slash 
    echo $new_url = implode('/', $url_array); 

輸出:

http://192.168.0.16/wordpress/blog 
0

正確的方法要使用parse_url()dirname(),這也將支持查詢參數。你可能會爆炸$uri['path'],但在這種情況下它是不必要的。

<?php 
// explode the uri in its proper parts 
$uri = parse_url('/wordpress/blog/page-2/?id=bla'); 

// remove last element 
$path = dirname($uri['path']); 

// incase you got query params, append them 
if (!empty($uri['query'])) { 
    $path .= '?'.$uri['query']; 
} 

// string(22) "/wordpress/blog?id=bla" 
var_dump($path); 

看到它的工作:https://3v4l.org/joJrF