Adding utm_source to url in custom text with php

So, we have a text in which there are links and you need to add an additional parameter of each link in the processing.
This function can help you:

function utm_source($content, $source, $campaign = false){
	$regexp = '/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i';
	$additional_url = 'utm_source=' . $source;
	if($campaign){
		$additional_url .= '&utm_campaign=' . $campaign;
	}
	$callback = function($matches) use ($additional_url){
		$url = $matches[1];
		$url = parse_url($url);
		if(isset($url['query'])){
			return $matches[1] . '&' . $additional_url;
		}else{
			return $matches[1] . '?' . $additional_url;
		}
	};
	$result = preg_replace_callback($regexp, $callback, $content);
	return $result;
}

Leave a Reply

Your email address will not be published. Required fields are marked *