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