phptext-parsingparse-url

Parse the query string of a string containing a relative URL


I have a variable in my PHP script called $url

Here's an example of how I use it:

<?php 
$url = '/test/?utm_source=test&utm_campaign=test2&utm_medium=test3";

I'd like to have a PHP snippet that grabs the valus of utm_source, utm_campaign & utm_medium. How do I achieve this?


Solution

  • Try This

    <?php 
    
    $url = "/test/?utm_source=test&utm_campaign=test2&utm_medium=test3";
    
    $url_parsed=parse_url($url);
    $query_params=[];
    $query_parsed=parse_str($url_parsed['query'],$query_params);
    
    echo $query_params['utm_source'].PHP_EOL.
        $query_params['utm_campaign'].PHP_EOL.
        $query_params['utm_medium'].PHP_EOL;
    ?>