<?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.
$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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With