michaelmcgurk
michaelmcgurk

Reputation: 6509

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?

Upvotes: 0

Views: 59

Answers (3)

AnTrakS
AnTrakS

Reputation: 743

Another way with explode function:

<?php 
$url = "/test/?utm_source=test&utm_campaign=test2&utm_medium=test3";
$params = explode("=", $url);

$utmSource = explode("&", $params[1]);
$utmCampaign = explode("&", $params[2]);
$utmMedium = $params[3];

Upvotes: 1

Ryan Lund
Ryan Lund

Reputation: 128

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;
?>

Upvotes: 1

SurfMan
SurfMan

Reputation: 1803

I have a feeling that the function parse_str() is exactly what you are looking for. See https://secure.php.net/manual/en/function.parse-str.php

Upvotes: 0

Related Questions