将查询字符串追加到任何形式的 URL

php
2022-08-30 15:56:20

我要求用户在文本框中输入URL,并需要向其附加查询字符串。

URL 的可能值可以是这样的:

  1. http://www.example.com

  2. http://www.example.com/a/

  3. http://www.example.com/a/?q1=one

  4. http://www.example.com/a.html

  5. http://www.example.com/a.html?q1=one

现在我需要向它添加查询字符串,如“q2=two”,这样输出就像:

  1. http://www.example.com/?q2=two

  2. http://www.example.com/a/?q2=two

  3. http://www.example.com/a/?q1=one&q2=two

  4. http://www.example.com/a.html?q2=two

  5. http://www.example.com/a.html?q1=one&q2=two

如何使用 PHP 实现以下目标?


答案 1
<?php

$urls = array(
         'http://www.example.com',
         'http://www.example.com/a/',
         'http://www.example.com/a/?q1=one',
         'http://www.example.com/a.html',
         'http://www.example.com/a.html?q1=one'
        );

$query = 'q2=two';

foreach($urls as &$url) {
   $parsedUrl = parse_url($url);
   if ($parsedUrl['path'] == null) {
      $url .= '/';
   }
   $separator = ($parsedUrl['query'] == NULL) ? '?' : '&';
   $url .= $separator . $query;
}

var_dump($urls);

输出

array(5) {
  [0]=>
  string(29) "http://www.example.com/?q2=two"
  [1]=>
  string(32) "http://www.example.com/a/?q2=two"
  [2]=>
  string(39) "http://www.example.com/a/?q1=one&q2=two"
  [3]=>
  string(36) "http://www.example.com/a.html?q2=two"
  [4]=>
  &string(43) "http://www.example.com/a.html?q1=one&q2=two"
}

密码键盘


答案 2

$url是您的网址。使用 strpos 函数

if(strpos($url,'?') !== false) {
   $url .= '&q2=two';
} else {
   $url .= '?q2=two';
}

推荐