ale*_*lex 34

<?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);
Run Code Online (Sandbox Code Playgroud)

产量

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"
}
Run Code Online (Sandbox Code Playgroud)

CodePad.

  • 您应该使用`(!array_key_exists('query',$ ParsedURL)|| is_null($ ParsedURL ['query']))`而不是`($ parsedUrl ['query'] == NULL)`以避免`undefined index`错误. (2认同)

Rap*_*tor 13

$ url是您的网址.使用strpos功能

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

  • 那应该是`strpos($ url,'?')!== false` (3认同)
  • 我唯一能看到此方法不起作用的情况是 URL 包含哈希片段。 (2认同)

Don*_*mmy 7

我知道这是旧的,但我改进了亚历克斯的答案,以解释字符串的"#"部分.

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

$query = 'q2=two';

foreach($urls as &$url) {
    $pound = "";
    $poundPos = -1;

    //Is there a #?
    if ( ( $poundPos = strpos( $url, "#" ) ) !== false )
    {
        $pound = substr( $url, $poundPos );
        $url = substr( $url, 0, $poundPos );
    }

    $separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
    $url .= $separator . $query . $pound;
}

var_dump($urls);
Run Code Online (Sandbox Code Playgroud)