link 中未正确添加附属标签

Affiliate tag is not adding properly in link

我正在尝试使用 php 创建附属 link 生成器,我正在使用以下代码生成。但是只有当 link 包含任何附属标签时,此代码才在 link 的最后添加 affid。如果我使用此 link 然后 'https://www.flipkart.com/whirlpool-1-5-ton-5-star-split-inverter-ac-white/p/itmf8fb8a675505d?pid=ACNFE6K2BXFY6EKX' 它会向我发送相同的 link 而不添加任何标签。

任何人都可以帮我解决这个问题?

$url = "https://www.flipkart.com/whirlpool-1-5-ton-5-star-split-inverter-ac-white/p/itmf8fb8a675505d?pid=ACNFE6K2BXFY6EKX";
      $afftag = 'harshk'; //our affiliate ID
        $affstring = 'affid='; // url parameter for affiliate ID
        if (parse_url($url, PHP_URL_QUERY)): //check if link has query string
            if (strpos($affstring, $url) !== true) : //check if link already has affiliate ID
                $url = preg_replace("/(".$affstring.").*?(\z|&)/", "".$afftag."", $url);
        else:
                $url = $url.'&'.$affstring.$afftag;
            endif;
        else:
            $url = $url.'?'.$affstring.$afftag;
        endif;

尝试一下是否有效

$url = "https://www.flipkart.com/whirlpool-1-5-ton-5-star-split-inverter-ac-white/p/itmf8fb8a675505d?pid=ACNFE6K2BXFY6EKX";
$afftag = 'harshk'; //our affiliate ID
$affstring = 'affid='; // url parameter for affiliate ID
if (parse_url($url, PHP_URL_QUERY)): //check if link has query string
    if (strpos($affstring, $url) === true) : //check if link already has affiliate ID
        $url = preg_replace("/(" . $affstring . ").*?(\z|&)/", "" . $afftag . "", $url);
    else:
        $url = $url . '&' . $affstring . $afftag;
    endif;
else:
    $url = $url . '?' . $affstring . $afftag;
endif;

解决方案#2

<?php

$urlStr = "https://www.flipkart.com/whirlpool-1-5-ton-5-star-split-inverter-ac-white/p/itmf8fb8a675505d?pid=ACNFE6K2BXFY6EKX";
$afftag = 'harshk'; //our affiliate ID
$affstring = 'affid'; // url parameter for affiliate ID
$url_components = parse_url($urlStr);
$params = [];
if (isset($url_components['query'])):
    parse_str($url_components['query'], $params);
endif;
$url = "{$url_components['scheme']}://{$url_components['host']}{$url_components['path']}";
$params[$affstring] = $afftag;
$url .= "?" . http_build_query($params);