如何在PHP中合并查询字符串

6tdlim6h  于 2023-06-20  发布在  PHP
关注(0)|答案(6)|浏览(93)

给定一个url和一个查询字符串,我如何获得由查询字符串和url组合得到的url?
我正在寻找类似于.htaccess的qsa的功能。我意识到这对于完全手工实现来说是相当微不足道的,但是有没有内置的函数来处理查询字符串,可以简化或完全解决这个问题?
示例输入/结果集:

Url="http://www.example.com/index.php/page?a=1"
QS ="?b=2"
Result="http://www.example.com/index.php/page?a=1&b=2"
Url="page.php"
QS ="?b=2"
Result="page.php?b=2"
0ve6wy6x

0ve6wy6x1#

不使用PECL扩展,也不是大量复制和粘贴函数的东西怎么样?它仍然有点复杂,因为您要将两个查询字符串拼接在一起,并且不希望使用$old .= $new;这样的方式
我们将使用parse_url从所需的url中提取查询字符串,使用parse_str解析要连接的查询字符串,使用array_merge将它们连接在一起,使用http_build_query创建新的组合字符串。

// Parse the URL into components
$url = 'http://...';
$url_parsed = parse_url($url);
$new_qs_parsed = array();
// Grab our first query string
parse_str($url_parsed['query'], $new_qs_parsed);
// Here's the other query string
$other_query_string = 'that=this&those=these';
$other_qs_parsed = array();
parse_str($other_query_string, $other_qs_parsed);
// Stitch the two query strings together
$final_query_string_array = array_merge($new_qs_parsed, $other_qs_parsed);
$final_query_string = http_build_query($final_query_string_array);
// Now, our final URL:
$new_url = $url_parsed['scheme'] 
         . '://'
         . $url_parsed['host'] 
         . $url_parsed['path'] 
         . '?'      
         . $final_query_string;
bjp0bcyl

bjp0bcyl2#

您可以使用以下命令从url获取查询字符串部分:

$_SERVER['QUERY_STRING']

然后正常地将其附加到URL。
如果你想在查询字符串中指定你自己的自定义变量,看看:

http_build_query

von4xj4u

von4xj4u3#

这是一系列从WordPress“框架”中提取的函数,可以做到这一点,但这可能太多了:

add_query_arg()

/**
 * Retrieve a modified URL query string.
 *
 * You can rebuild the URL and append a new query variable to the URL query by
 * using this function. You can also retrieve the full URL with query data.
 *
 * Adding a single key & value or an associative array. Setting a key value to
 * emptystring removes the key. Omitting oldquery_or_uri uses the $_SERVER
 * value.
 *
 * @since 1.0
 *
 * @param mixed $param1 Either newkey or an associative_array
 * @param mixed $param2 Either newvalue or oldquery or uri
 * @param mixed $param3 Optional. Old query or uri
 * @return string New URL query string.
 */
public function add_query_arg() {
    $ret = '';
    if ( is_array( func_get_arg(0) ) ) {
        $uri = ( @func_num_args() < 2 || false === @func_get_arg( 1 ) ) ? $_SERVER['REQUEST_URI'] : @func_get_arg( 1 );
    } else {
        $uri = ( @func_num_args() < 3 || false === @func_get_arg( 2 ) ) ? $_SERVER['REQUEST_URI'] : @func_get_arg( 2 );
    }

    if ( $frag = strstr( $uri, '#' ) ) {
        $uri = substr( $uri, 0, -strlen( $frag ) );
    } else {
        $frag = '';
    }

    if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
        $protocol = $matches[0];
        $uri = substr( $uri, strlen( $protocol ) );
    } else {
        $protocol = '';
    }

    if ( strpos( $uri, '?' ) !== false ) {
        $parts = explode( '?', $uri, 2 );
        if ( 1 == count( $parts ) ) {
            $base = '?';
            $query = $parts[0];
        } else {
            $base = $parts[0] . '?';
            $query = $parts[1];
        }
    } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
        $base = $uri . '?';
        $query = '';
    } else {
        $base = '';
        $query = $uri;
    }

    parse_str( $query, $qs );

    if ( get_magic_quotes_gpc() )
        $qs = format::stripslashes_deep( $qs );

    $qs = format::urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
    if ( is_array( func_get_arg( 0 ) ) ) {
        $kayvees = func_get_arg( 0 );
        $qs = array_merge( $qs, $kayvees );
    } else {
        $qs[func_get_arg( 0 )] = func_get_arg( 1 );
    }

    foreach ( ( array ) $qs as $k => $v ) {
        if ( $v === false )
            unset( $qs[$k] );
    }

    $ret = http_build_query( $qs, '', '&' );
    $ret = trim( $ret, '?' );
    $ret = preg_replace( '#=(&|$)#', '$1', $ret );
    $ret = $protocol . $base . $ret . $frag;
    $ret = rtrim( $ret, '?' );
    return $ret;
}

stripslashes_deep()

/**
 * Navigates through an array and removes slashes from the values.
 *
 * If an array is passed, the array_map() function causes a callback to pass the
 * value back to the function. The slashes from this value will removed.
 *
 * @since 1.0
 *
 * @param array|string $value The array or string to be stripped
 * @return array|string Stripped array (or string in the callback).
 */
function stripslashes_deep( $value ) {
    return is_array( $value ) ? array_map( array('self', 'stripslashes_deep'), $value ) : stripslashes( $value );
}

urlencode_deep()

/**
 * Navigates through an array and encodes the values to be used in a URL.
 *
 * Uses a callback to pass the value of the array back to the function as a
 * string.
 *
 * @since 1.0
 *
 * @param array|string $value The array or string to be encoded.
 * @return array|string $value The encoded array (or string from the callback).
 */
public function urlencode_deep( $value ) {
    return is_array($value) ? array_map( array('self', 'urlencode_deep'), $value) : urlencode($value);
}
e0uiprwp

e0uiprwp4#

没有内置的函数可以做到这一点。但是,您可以从http PECL扩展中使用此函数,
http://usphp.com/manual/en/function.http-build-url.php
比如说

$url = http_build_url("http://www.example.com/index.php/page?a=1",
    array(
        "b" => "2"
    )
);
3okqufwl

3okqufwl5#

如果URL冲突会发生什么?如果两个url都在querystring中包含b=组件?你需要决定哪一个占主导地位。
这里有一段代码可以完成你想要的任务,将每个字符串解析为一个url,然后提取query url部分并将它们重新组合在一起。

$url="http://www.example.com/index.php/page?a=1";
$qs ="?b=2";

$url_parsed = parse_url($url);
$qs_parsed = parse_url($qs);

$args = array(
    $url_parsed['query'],
    $qs_parsed['query'],
);

$new_url = $url_parsed['scheme'];
$new_url .= '://';
$new_url .= $url_parsed['host'];
$new_url .= $url_parsed['path'];
$new_url .= '?';
$new_url .= implode('&', $args);

print $new_url;
0h4hbjxa

0h4hbjxa6#

这里是另一个函数来合并现有的URL参数

public function mergeParamsToUrl(string $url, array $params)
    {
        $urlParts = parse_url($url);

        // Combine existing query string with new parameters
        $existingParams = [];
        if (isset($urlParts['query'])) {
            parse_str($urlParts['query'], $existingParams);
        }

        $mergedParams = array_merge($existingParams, $params);
        $mergedQueryString = http_build_query($mergedParams);

        // Reconstruct the URL
        $mergedUrl = "{$urlParts['scheme']}://{$urlParts['host']}{$urlParts['path']}";
        if ($mergedQueryString) {
            $mergedUrl .= '?'.$mergedQueryString;
        }

        if (isset($urlParts['fragment'])) {
            $mergedUrl .= '#'.$urlParts['fragment'];
        }

        return $mergedUrl;
    }

相关问题