简体   繁体   English

如何将 Google 标签管理器的初始流量来源 cookie 值转换为数组?

[英]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.我已经使用 UTMZ Cookie Replicator 的一些第三方代码为 Google 标签管理器安装了“cookie 创建”代码。 It sets a cookie and starts collecting the initial traffic source for a user visiting a website.它设置 cookie 并开始为访问网站的用户收集初始流量来源。 My website is https://www.palmerstonmoving.ca .我的网站是https://www.palmerstonmoving.ca

The cookie name is InitialTrafficSource , and the value returned is cookie 名称为InitialTrafficSource ,返回的值为

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:如何获取 cookie 返回的字符串值并将其转换为某种 PHP 代码,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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