开发者

How to check wether an URL already has a parameter inside it?

Using PHP I need to check whether an URL I am appending information to already has a parameter or not.

So if the URL is

http://test.com开发者_StackOverflow社区/url?a=1

I would need to add on &b=2, ie

http://test.com/url?a=1&b=2

However if the URL was

http://test.com/url

I would need to append

http://test.com/url?b=2

Is it possible to check for this within PHP? In summary I need to attach the b=2 parameter using the correct separator character ("?" if there was none in the existing link or "&" if there is already a "?" in the existing link).


Do not check but assemble a new one
use $_GET array and http_build_query() function


You could use parse_url(). Then use parse_str() to get the query pieces, modify the array and use http_build_query() to recreate the query string.


With this function, you can call set('b', 2) or set multiple values at once with set(array('a' => 1, 'b' => 2, 'c' => 3)).

function set($name, $value='', $vars='') {
    if (!$vars) $vars = $_SERVER['QUERY_STRING'];
    parse_str($vars, $a);
    if (!is_array($name)) $name = array($name => $value);
    foreach ($name as $k => $v) {
        $a[$k] = $v;
        if ($v === '') unset($a[$k]);
    }
    $q = '';
    foreach ($a as $k => $v) $q .= ($q ? '&' : '') . $k . '=' . $v;
    return $q ? '?' . $q : '';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜