tags:

views:

43

answers:

3

How should I go about appending to the end of all urls in string of html that is about to be sent out as as email? I want to add the google analytics campaign tracking to it like this:
?utm_source=email&utm_medium=email&utm_campaign=product_notify

99% of the pages will not end in '.html' and some urls might already have things like ?sr=1 at the end of them.

A: 

You can use the following snippet, to append your google analytics GET parameters to the existing parameters of the current script URI.

function getQuery() {

 $url = parse_url($_SERVER['REQUEST_URI']);

 return $url['query'].'&utm_source=email&utm_medium=email&utm_campaign=product_notify';
}
softcr
Nice, but not what I'm looking for. The urls I want to append to are in a string of html.
Echo
+1  A: 

Well... You could do something like this:

function AppendCampaignToString($string) {
    $regex = '#(<a href=")([^"]*)("[^>]*?>)#i';
    return preg_replace_callback($regex, '_appendCampaignToString', $string);
}
function _AppendCampaignToString($match) {
    $url = $match[2];
    if (strpos($url, '?') === false) {
        $url .= '?';
    }
    $url .= '&utm_source=email&utm_medium=email&utm_campaign=product_notify';
    return $match[1].$url.$match[3];
}

That should automatically find all the links on the page (even external ones, so be careful). The ? check just makes sure that we append a query string on to it...

Edit: Fixed issue in the regex that didn't work as intended.

ircmaxell
Wonderful. Thanks.
Echo
Hmmm, should a utm_source possibly overwrite an already given one, be appended (PHP can't handle that in the $_GET array), or the other way around?
Wrikken
A: 
<?php
$add = array(
 'utm_source'=>'email',
 'utm_medium'=>'email'
 'utm_campaign'=>'product_notify');
$doc = new DOMDocument();
$doc->loadHTML('your html');
foreach($doc->getElementsByTagName('a') as $link){
    $url = parse_url($link->getAttribute('href'));
    $gets = isset($url['query']) ? array_merge(parse_str($url['query'])) : $add;
    $newstring = '';
    if(isset($url['scheme'])) $newstring .= $url['scheme'].'://';
    if(isset($url['host']))   $newstring .= $url['host'];
    if(isset($url['port']))   $newstring .= ':'.$url['port'];
    if(isset($url['path']))   $newstring .= $url['path'];
    $newstring .= '?'.http_build_query($gets);
    if(isset($url['fragment']))   $newstring .= '#'.$url['fragment'];
    $link->setAttribute('href',$newstring);
 }
 $html - $doc->saveHTML();
 ?>
Wrikken