简体   繁体   中英

How can I convert a Google Tag Manager's Initial Traffic Source cookie values to an array?

I have installed a 'cookie creating' code for Google Tag Manager, using some third party code from UTMZ Cookie Replicator. It sets a cookie and starts collecting the initial traffic source for a user visiting a website. My website is https://www.palmerstonmoving.ca .

The cookie name is InitialTrafficSource , and the value returned is

utmcsr=(direct)|utmcmd=(none)|utmccn=(not set)

How can I get the string values returned by the cookie and convert it to some sort of PHP code, for example:

$utmcsr= 'direct',
$utmcmd= 'none',
$utmccn= 'not set',

There're many ways to do it and I wonder why you didn't even try one (using basic string functions for instance).

With basic functions:

$str = 'utmcsr=(direct)|utmcmd=(none)|utmccn=(not set)';

$result = [];

foreach (explode('|', $str) as $item) {
    list($key, $val) = explode('=', $item);
    $result[$key] = trim($val, '()');
}

print_r($result);

A way that splits the string on |and that uses a formatted string to extract the key/value for each item:

$str = 'utmcsr=(direct)|utmcmd=(none)|utmccn=(not set)';

$format = '%[^=]=(%[^)])';
$result = [];

foreach (explode('|', $str) as $v) {
    [$key, $result[$key]] = sscanf($v, $format);
}

print_r($result);

The same written in a functional way:

$result = array_reduce(explode('|', $str), function ($c, $i) {
    [$key, $c[$key]] = sscanf($i, '%[^=]=(%[^)]');
    return $c;
}, []);

With a regex:

$str = 'utmcsr=(direct)|utmcmd=(none)|utmccn=(not set)';

preg_match_all('~ (?<key> [^|=]+ ) = \( (?<val> [^)]* ) \) ~x', $str, $matches);

$result = array_combine($matches['key'], $matches['val']);

print_r($result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM