phppreg-replacestr-replaceaffiliate

Add deep links to flipkart affiliate link


I am trying to create a affiliate link geenrator using php. I need help to create a flipkart deep affiliate link,which can remove 'www.' and add 'dl.' if present or add 'dl.' before link. For example if input link was https://www.flipkart.com/?affid=xyz then it sends me https://dl.flipkart.com/dl/?affid=xyz . Same for the below links :-
Input link ---> Output Link
https://flipkart.com/?affid=xyz --> https://dl.flipkart.com/dl/?affid=xyz , or
https://dl.flipkart.com/?affid=xyz --> https://dl.flipkart.com/dl/?affid=xyz , or
https://dl.flipkart.com/?affid=xyz --> https://dl.flipkart.com/dl/?affid=xyz

Thanks in advance.


Solution

  • Use parse_url() to get the url metadata. Now, check for host and just overwrite it with dl.flipkart.com and so goes for the path as well.

    Snippet:

    <?php
    
    $tests = [
            'https://www.flipkart.com/?affid=xyz',
            'https://flipkart.com/dl?affid=xyz',
            'https://dl.flipkart.com/?affid=xyz',
            'https://dl.flipkart.com/?affid=xyz',
            'https://dl.flipkart.com/dl?affid=xyz',
            'https://flipkart.com/whirlpool-1-5-ton-5-star-split-inverter-ac-white/p/itmf8fb8a675505d?pid=ACNFE6K2BXFY6EKX'
        ];
        
    foreach($tests as $test){
        echo $test," => ",getNewURL($test),PHP_EOL;
    }
    
    function getNewURL($url){
        $url_parts = parse_url($url);
        $url_parts['host'] = 'dl.flipkart.com';
        $url_parts['path'] .= "/";
        if(strpos($url_parts['path'],"/dl/") !== 0) $url_parts['path'] = '/dl/'.trim($url_parts['path'],"/");
    
        return $url_parts['scheme'] . "://" . $url_parts['host'] . $url_parts['path'] . (empty($url_parts['query']) ? '' : '?' . $url_parts['query']); 
    }