php 如何删除查询字符串并仅获取网址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6969645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:42:43  来源:igfitidea点击:

How to remove the querystring and get only the url?

phpquery-string

提问by Navi Gamage

Im using PHP to build the URL of the current page. Sometimes, URLs in the form of

我使用 PHP 来构建当前页面的 URL。有时,URL 形式为

www.mydomian.com/myurl.html?unwantedthngs

are requested. I want to remove the ?and everything that follows it (querystring), such that the resulting URL becomes:

被要求。我想删除?和它后面的所有内容(查询字符串),这样生成的 URL 变为:

www.mydomain.com/myurl.html

My current code is this:

我目前的代码是这样的:

<?php
function curPageURL() {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {
        $pageURL .= "s";
    }
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" .
            $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}
?>

回答by RiaD

You can use strtokto get string before first occurence of ?

您可以使用strtok在第一次出现之前获取字符串?

$url = strtok($_SERVER["REQUEST_URI"], '?');

strtok()represents the most concise technique to directly extract the substring before the ?in the querystring. explode()is less direct because it must produce a potentially two-element array by which the first element must be accessed.

strtok()表示直接提取?查询字符串中 之前的子字符串的最简洁的技术。 explode()不太直接,因为它必须生成一个潜在的二元素数组,必须通过该数组访问第一个元素。

Some other techniques may break when the querystring is missing or potentially mutate other/unintended substrings in the url -- these techniques should be avoided.

当查询字符串丢失或潜在地改变 url 中的其他/意外子字符串时,其他一些技术可能会中断——这些技术应该避免。

A demonstration:

一个演示

$urls = [
    'www.example.com/myurl.html?unwantedthngs#hastag',
    'www.example.com/myurl.html'
];

foreach ($urls as $url) {
    var_export(['strtok: ', strtok($url, '?')]);
    echo "\n";
    var_export(['strstr/true: ', strstr($url, '?', true)]); // not reliable
    echo "\n";
    var_export(['explode/2: ', explode('?', $url, 2)[0]]);  // limit allows func to stop searching after first encounter
    echo "\n";
    var_export(['substr/strrpos: ', substr($url, 0, strrpos( $url, "?"))]);  // not reliable; still not with strpos()
    echo "\n---\n";
}

Output:

输出:

array (
  0 => 'strtok: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'strstr/true: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'explode/2: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'substr/strrpos: ',
  1 => 'www.example.com/myurl.html',
)
---
array (
  0 => 'strtok: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'strstr/true: ',
  1 => false,                       // bad news
)
array (
  0 => 'explode/2: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'substr/strrpos: ',
  1 => '',                          // bad news
)
---

回答by veritas

Use PHP Manual - parse_url()to get the parts you need.

使用PHP 手册 - parse_url()获取您需要的部分。

Edit (example usage for @Navi Gamage)

编辑(@Navi Gamage 的示例用法)

You can use it like this:

你可以这样使用它:

<?php
function reconstruct_url($url){    
    $url_parts = parse_url($url);
    $constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];

    return $constructed_url;
}

?>

Edit (second full example):

编辑(第二个完整示例):

Updated function to make sure scheme will be attached and none notice msgs appear:

更新功能以确保将附加方案并且不会出现任何通知消息:

function reconstruct_url($url){    
    $url_parts = parse_url($url);
    $constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . (isset($url_parts['path'])?$url_parts['path']:'');

    return $constructed_url;
}


$test = array(
    'http://www.mydomian.com/myurl.html?unwan=abc',
    'http://www.mydomian.com/myurl.html',
    'http://www.mydomian.com',
    'https://mydomian.com/myurl.html?unwan=abc&ab=1'
);

foreach($test as $url){
    print_r(parse_url($url));
}       

Will return:

将返回:

Array
(
    [scheme] => http
    [host] => www.mydomian.com
    [path] => /myurl.html
    [query] => unwan=abc
)
Array
(
    [scheme] => http
    [host] => www.mydomian.com
    [path] => /myurl.html
)
Array
(
    [scheme] => http
    [host] => www.mydomian.com
)
Array
(
    [path] => mydomian.com/myurl.html
    [query] => unwan=abc&ab=1
)

This is the output from passing example urls through parse_url() with no second parameter (for explanation only).

这是通过 parse_url() 传递示例 url 的输出,没有第二个参数(仅用于解释)。

And this is the final output after constructing url using:

这是使用以下方法构建 url 后的最终输出:

foreach($test as $url){
    echo reconstruct_url($url) . '<br/>';
}   

Output:

输出:

http://www.mydomian.com/myurl.html
http://www.mydomian.com/myurl.html
http://www.mydomian.com
https://mydomian.com/myurl.html

回答by Ludo - Off the record

best solution:

最佳解决方案:

echo parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

No need to include your http://domain.comin your if you're submitting a form to the same domain.

如果您要向同一域提交表单,则无需在您的http://domain.com中包含。

回答by zellio

$val = substr( $url, 0, strrpos( $url, "?"));

回答by Mukesh Saxena

Most Easiest Way

最简单的方法

$url = 'https://www.youtube.com/embed/ROipDjNYK4k?rel=0&autoplay=1';
$url_arr = parse_url($url);
$query = $url_arr['query'];
print $url = str_replace(array($query,'?'), '', $url);

//output
https://www.youtube.com/embed/ROipDjNYK4k

回答by James Bordine II

You'll need at least PHP Version 5.4 to implement this solution without exploding into a variable on one line and concatenating on the next, but an easy one liner would be:

您至少需要 PHP 5.4 版才能实现此解决方案,而不会在一行上分解为变量并在下一行连接,但一个简单的一行代码是:

$_SERVER["HTTP_HOST"].explode('?', $_SERVER["REQUEST_URI"], 2)[0];

Server Variables: http://php.net/manual/en/reserved.variables.server.php
Array Dereferencing: https://wiki.php.net/rfc/functionarraydereferencing

服务器变量:http: //php.net/manual/en/reserved.variables.server.php
数组解引用:https: //wiki.php.net/rfc/functionarraydereferencing

回答by Mohammad altenji

You can use the parse_url build in function like that:

您可以像这样使用 parse_url 内置函数:

$baseUrl = $_SERVER['SERVER_NAME'] . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

回答by ysrb

You can try:

你可以试试:

<?php
$this_page = basename($_SERVER['REQUEST_URI']);
if (strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
?>

回答by user1079877

If you want to get request path (more info):

如果您想获取请求路径(更多信息):

echo parse_url($_SERVER["REQUEST_URI"])['path']

If you want to remove the query and (and maybe fragment also):

如果您想删除查询和(也可能是片段):

function strposa($haystack, $needles=array(), $offset=0) {
        $chr = array();
        foreach($needles as $needle) {
                $res = strpos($haystack, $needle, $offset);
                if ($res !== false) $chr[$needle] = $res;
        }
        if(empty($chr)) return false;
        return min($chr);
}
$i = strposa($_SERVER["REQUEST_URI"], ['#', '?']);
echo strrpos($_SERVER["REQUEST_URI"], 0, $i);

回答by Ryan Prechel

To remove the query string from the request URI, replace the query string with an empty string:

要从请求 URI 中删除查询字符串,请将查询字符串替换为空字符串:

function request_uri_without_query() {
    $result = $_SERVER['REQUEST_URI'];
    $query = $_SERVER['QUERY_STRING'];
    if(!empty($query)) {
        $result = str_replace('?' . $query, '', $result);
    }
    return $result;
}