Reputation: 3927
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.
Upvotes: 6
Views: 4109
Reputation: 70460
<?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();
?>
Upvotes: 2
Reputation: 10342
Here is mine solution, simple question but quite complex solution working all over URL types with
$campaign = (object)['utm_source' => 'email', 'utm_medium' => 'email', 'utm_campaign' => 'abc'];
$host = 'www.me.com';
$html = preg_replace_callback(
'#(<a.*?href=["\']?)(?<href>https?://[^\s"\']+)(["\']?.*?>.*?</a>)#si', function ($matches) use ($campaign, $host) {
$url = parse_url($matches['href']);
// if (isset($url['host']) && $url['host'] !== $host) return $matches[0];
parse_str(isset($url['query']) ? $url['query'] : '', $query);
$query = array_merge(
$query, array_filter(
[
'utm_source' => $campaign->utm_source,
'utm_medium' => $campaign->utm_medium,
'utm_term' => $campaign->utm_term,
'utm_content' => $campaign->utm_content,
'utm_campaign' => $campaign->utm_campaign,
]
)
);
return $matches[1] . // anchor part before url
(isset($url['scheme']) ? $url['scheme'] . '://' : '') .
(isset($url['user']) ? $url['user'] : '') .
(isset($url['pass']) ? (isset($url['user']) ? ':' : '') . $url['pass'] : '') .
(isset($url['user']) || isset($url['pass']) ? '@' : '').
(isset($url['host']) ? $url['host'] : '') .
(isset($url['port']) ? ':' . $url['port'] : '') .
(isset($url['path']) ? $url['path'] : '') .
'?' . http_build_query($query) .
(isset($url['fragment']) ? '#' . $url['fragment'] : '') .
$matches[3]; // anchor part after URL
}, $html
);
Last part (concat URL) can be also replaced with http_build_url()
but you will need HTTP extension enabled.
Code was tested on follow URLs:
<a href="http://www.me.com">Lorem</a>
<a href="http://www.me.com/">ipsum</a>
<a href="http://www.me.com/#section-2">dolor</a>
<a href="http://www.me.com/path-to-somewhere/file.php">sit</a>
<a href="http://www.me.com/?">amet</a>
<a href="http://www.me.com/?foo=bar">consectetur</a>
<a href="http://www.me.com/?foo=bar&bar=foo">consectetur</a>
<a href="http://www.NOTME.com?utm_source=XXX&utm_medium=XXX&utm_campaign=XXX">existing utm params</a>
<a href="http://user:[email protected]/?foo=bar#section-3">elit</a>
<a href="http://user:@www.me.com/?foo=bar#section-3">elit</a>
<a href="http://[email protected]?foo=bar#section-3">elit</a>
with following results:
<a href="http://www.me.com?utm_source=email&utm_medium=email&utm_campaign=abc">Lorem</a>
<a href="http://www.me.com/?utm_source=email&utm_medium=email&utm_campaign=abc">ipsum</a>
<a href="http://www.me.com/?utm_source=email&utm_medium=email&utm_campaign=abc#section-2">dolor</a>
<a href="http://www.me.com/path-to-somewhere/file.php?utm_source=email&utm_medium=email&utm_campaign=abc">sit</a>
<a href="http://www.me.com/?utm_source=email&utm_medium=email&utm_campaign=abc">amet</a>
<a href="http://www.me.com/?foo=bar&utm_source=email&utm_medium=email&utm_campaign=abc">consectetur</a>
<a href="http://www.me.com/?foo=bar&bar=foo&utm_source=email&utm_medium=email&utm_campaign=abc">consectetur</a>
<a href="http://www.NOTME.com?utm_source=email&utm_medium=email&utm_campaign=abc">existing utm params</a>
<a href="http://user:[email protected]/?foo=bar&utm_source=email&utm_medium=email&utm_campaign=abc#section-3">elit</a>
<a href="http://user:@www.me.com/?foo=bar&utm_source=email&utm_medium=email&utm_campaign=abc#section-3">elit</a>
<a href="http://[email protected]?foo=bar&utm_source=email&utm_medium=email&utm_campaign=abc#section-3">elit</a>
As you can notice, my code works for all links in HTML (not just me.com) if you want filter hostname uncomment line right after parse_url()
.
Upvotes: 1
Reputation: 2487
Update to @ircmaxell's answer, regex now matches even when there are attributes on the before href & code simplification.
/**
* @param string $body
* @param string $campaign
* @param string $medium
* @return mixed
*/
protected function add_analytics_tracking_to_urls($body, $campaign, $medium = 'email') {
return preg_replace_callback('#(<a.*?href=")([^"]*)("[^>]*?>)#i', function($match) use ($campaign, $medium) {
$url = $match[2];
if (strpos($url, '?') === false) {
$url .= '?';
} else {
$url .= '&';
}
$url .= 'utm_source=' . $medium . '&utm_medium=' . $medium . '&utm_campaign=' . urlencode($campaign);
return $match[1] . $url . $match[3];
}, $body);
}
Upvotes: 9
Reputation: 1439
My solution I've built & tested last night:
I match only the links which DO NOT already have "utm_" like query parameters, but includes links with "utm_" as a part of the path: before query params or substring of another param name like "xutm_".
For this I've used a combination of positive and negative RegEx lookahead assertions (http://php.net/manual/en/regexp.reference.assertions.php)
I have also allowed tags to have other attributes before and after href
$pattern = '/<a[^>]*href="(?=(.(?!(\?|&)utm_))*?>)[^"]*/i';
Which matches all links which do NOT have '?utm_' nor '&utm_' in href tag
Then I use a class callback function solution in order to be able pass the query parameters to be appended (as extra parameters to the callback)
class link_params{
private $parameters;
function __construct($params){
$this->parameters = $params;
}
function callback($matches){
return $matches[0] . (preg_match('/\\?[^"]/', $matches[0]) ? '&' : '?') . http_build_query($this->parameters);
}
}
Prepare query parameters that I want to add to links:
$params_to_add = array(
'utm_source' => 'newsletter-sep13',
'utm_medium' => 'email',
'utm_campaign' => 'product-X'
);
$callback_helper = new link_params($params_to_add);
In the end I apply the preg_replace_callback function like this:
$html = preg_replace_callback($pattern, array($callback_helper, 'callback'), $html);
Upvotes: 0
Reputation: 165191
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.
Upvotes: 6
Reputation: 620
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';
}
Upvotes: 0