skip to Main Content

hello i want want to overwrite all peramters from old link to new link .. like

$oldURl="https://example.com/abcd/data?p=123&x=ABCDSS";

$newUrl="https://example.com/?data=1&data2=2&data3=3";

// $fnialurl=rewrite_data($oldURl,$newUrl);

final result i want ..
https://example.com/abcd/data?data=1&data2=2&data3=3&p=123&x=ABCDSS

you have any idea to get path & request from old url and replace it in new url

2

Answers


  1. I guess you could just use parse_url to achieve this. Loop all the url’s you want to join combining all their paths and queries then output them again at the end – they’d need to be passed in the order you want to join them however and the same host is expected in this example but it should get you started.

    function rewrite_data(string ...$urls): string
    {
        $paths = [];
        $queries = [];
        $key = parse_url(current($urls));
        
        foreach ($urls as $url)
        {
            $parsedUrl = parse_url($url);
            $paths[] = $parsedUrl['path'] ?? null;
            $queries[] = $parsedUrl['query'] ?? null;
        }
        
        [$paths, $queries] = [array_filter($paths, fn($x) => $x && $x !== '/'), array_filter($queries)];
        
        return sprintf('%s://%s%s?%s', $key['scheme'], $key['host'], implode('/', $paths), implode('&', $queries));
    }
    

    Usage in your example would be:

    # output: https://example.com/abcd/data?data=1&data2=2&data3=3&p=123&x=ABCDSS
    rewrite_data('https://example.com/?data=1&data2=2&data3=3', 'https://example.com/abcd/data?p=123&x=ABCDSS');
    

    See it working over on 3v4l.org

    Login or Signup to reply.
  2. Use parse_url with component arguments.

    $oldUrl = "https://example.com/abcd/data?p=123&x=ABCDSS";
    $newUrl = "https://example.com/?data=1&data2=2&data3=3";
    
    $baseUrl  = strtok($oldUrl, '?');
    $oldQuery = parse_url($oldUrl, PHP_URL_QUERY);
    $newQuery = parse_url($newUrl, PHP_URL_QUERY);
    
    $finalUrl = "{$baseUrl}?{$newQuery}&{$oldQuery}"; 
    
    echo $finalUrl;
    // https://example.com/abcd/data?data=1&data2=2&data3=3&p=123&x=ABCDSS
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search