Removing utm source via php / regex

孤者浪人 提交于 2021-02-08 04:38:22

问题


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


回答1:


$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.




回答2:


Use strtok to get the url as you like

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



回答3:


Figured out:

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

?>



回答4:


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


来源:https://stackoverflow.com/questions/31647926/removing-utm-source-via-php-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!