Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing utm source via php / regex

Tags:

regex

php

<?php
$before='http://www.urchin.com/download.html? utm_source=google&utm_medium=email&utm_campaign=product';
    $after = preg_replace('[?]utm_source=.*/','', $before);
 echo $after;
?>

Hi all,

How can I remove UTM tracking from URL via PHP/Regex in the above code example?

New to PHP so please explain your answer.

Thanks in advance!

Edit: Got a bit closer but still getting errors.

like image 480
KBS Avatar asked Aug 31 '25 16:08

KBS


2 Answers

$url = strtok($url, '?');

You can read more about strtok here.

Update: If you need to remove only utm_ params, you can use regular expression, e.g.:

$url = preg_replace( '/&?utm_.+?(&|$)$/', '', $url );

Note: This regex will remove any utm_ parameter from your URL.

like image 197
Kristian Vitozev Avatar answered Sep 02 '25 07:09

Kristian Vitozev


Here is my solution how to remove all UTM params from URL including hash UTM parameters:

<?php

$urls = [
    'https://www.someurl.com/?utm_medium=flow&red=true&article_id=5456#omg&utm_medium=email',
    'https://www.someurl.com/#utm_medium=flow&utm_medium=email',
    'https://www.someurl.com/?articleid=1235&utm_medium=flow&utm_medium=email',
    'https://www.someurl.com/?utm_medium=flow&articleid=1235&utm_medium=email',
    'https://www.someurl.com/?utm_medium=encoding%20space%20works&encoding=works%20also'
];

foreach ($urls as $url) {
    echo rtrim(preg_replace('/utm([_a-z0-9=%]+)\&?/', '', $url), '&?#') . PHP_EOL;
}
like image 27
OzzyCzech Avatar answered Sep 02 '25 08:09

OzzyCzech