使用php打印删除url的部分



我想使用php撤销页面url,但我希望删除的一些部分

<?php print("http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); ?>

Example: http://url.com/questions/page/112/
Result: http://url.com/page/112/

我想删除url中的questions/。我该怎么做?

$url="http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
$url=str_replace('/questions','',$url);
echo $url;

您需要使用mod_rewrite,这是apache中可用的模块。这将由web目录中的.htaccess文件管理。AddedBytes为初学者提供了一个很好的url重写教程。

查看此网站了解的详细信息

我会使用php的分解函数将示例拆分为一个由"/"s分隔的数组,然后在数组中循环,其中数组值=问题,取消设置或从数组中删除它。

//示例1

$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

下面是一个例子。

如果您只是想将其作为字符串删除,可以使用

$url = str_replace('/questions', '', $_SERVER["REQUEST_URI"]);

如果您想将用户重定向到该页面,您需要发送一个标题(在任何输出之前):

header('Location: http://' . $_SERVER["HTTP_HOST"] . $url);
exit;

试试这个;

$str = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
$parts = explode("/",$str);
$tmp = array();
for($i = 0; $i<count($parts)-2;$i++){
   $tmp[$i] = $parts[$i];
}
$output = implode("/",$tmp);

您可以使用类似的东西

$sentence = str_replace('questions/', '', 'http://url.com/questions/page/112/');
//This splits the uri into an array
$uri = explode("/",$_SERVER["REQUEST_URI"]);
//Then Remove the first part of the uri (ie questions)
$first_uri = array_shift($uri);
//Recreate the string from the array
$uri = implode("/", $uri);
//Print like in your example
print("http://" . $_SERVER["HTTP_HOST"] . $uri);
//You can also access the remove string (questions) in the $first_uri variable
print($first_uri); //returns questions
$url='http://'.$_SERVER['HTTP_HOST'].preg_replace('/^/questions/i','',$_SERVER['REQUEST_URI']);
echo $url;

最新更新