0

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?

1

3 Answers 3

1

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;
?>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

3 Comments

Oddly, here's my code: <?php $url = "/test/?utm_source=test&UTM_campaign=test2&utm_medium=test3"; parse_str($url); echo $utm_source."<br>"; echo $utm_campaign."<br>"; echo $utm_medium."<br>"; This doesn't work. It only outputs the las one :(
Please don't share your feelings -its easy to check the facts (parse_str() is the wrong function for the data in the question,)
Funny how the accepted answer uses said function. Ah well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.