将值添加到URL中的查询字符串

时间:2012-02-01 17:56:53

标签: php regex

  

可能重复:
  Change single variable value in querystring

我正在检索当前网址:

http://example.com/?s=original&fq=category

现在我想为s=

插入一个额外的参数
s=original+additional&fq=category

如果有人知道这一点,我们将不胜感激!

修改

这是在PHP WordPress环境中。我很想坚持使用PHP Regex,因为我不确定如何使用jQuery / js

4 个答案:

答案 0 :(得分:5)

不明确要求正则表达式的解决方案:

$old   = 'http://example.com/?s=original&fq=category';
$parts = parse_url($old);

parse_str($parts['query'], $query);
$query['s'] .= ' additional';

$new = sprintf(
  '%s://%s%s?%s'
    , $parts['scheme']
    , $parts['host']
    , $parts['path']
    , http_build_query($query)
);

echo 'Old: ', $old, PHP_EOL, 'New: ', $new, PHP_EOL;

以上代码输出:

Old: http://example.com/?s=original&fq=category
New: http://example.com/?s=original+additional&fq=category

答案 1 :(得分:3)

PHP内置了解析和重建URL的函数:

$bits = parse_url($url);
$args = parse_str($bits['query']);

$args['s'] .= 'morestuff';

$bits['query'] = http_build_query($args);
$new_url = http_build_url($bits);

答案 2 :(得分:1)

preg_replace($s, '/([?&]s=)([^&]+)/', '$1$2+additional');

快速PowerShell测试:

PS> $urls = 'http://example.com/?s=original&fq=category', 'http://example.com/?a=original&s=foo&fq=category'
PS> $urls -replace '([?&]s=)([^&]+)', '$1$2+additional'
http://example.com/?s=original+additional&fq=category
http://example.com/?a=original&s=foo+additional&fq=category

答案 3 :(得分:0)

你可以这个preg_replace:

$url = 'http://example.com/?s=original&fq=category';
$regex = '~([&?]s=)([^&]*)(&|$)~i';
$url = preg_replace($regex, '$1$2+additional$3', $url);
var_dump($url);

<强>输出:

string(53) "http://example.com/?s=original+additional&fq=category"