PHP:拆分cookie值并计数部分 [英] PHP: Split cookie value and count parts
问题描述
我是PHP初学者,希望这里有人可以帮助我。
I am a PHP beginner and hope someone here can help me with this.
我有一个类似于以下示例的字符串,其中分隔符是一个下划线,并且字符串的长度可以变化。
这三个数字是ID,括号中的数字是计数。
I have a string that looks like the following example where the separator is an underscore and the length of the string can vary. The three digit numbers are IDs and the numbers in brackets are counts.
示例: 101(2)_102(3)_103(5)
我正在寻找一种拆分方式,以便可以访问每个ID和每个计数,以便将其用于进一步的计算等等。
我尝试使用explode,但是无法正常工作。
I am looking for a way to split this in a way that I can access each ID and each count in order to use them for further calculations etc. I tried using explode but couldn't get this to work.
我的尝试
print_r(explode("_", $_COOKIE['myCookieName']));
我假设我需要在此处创建一个数组。
I assume I need to create an array here.
预期输出(示例): 总ID:3,总数:10
有人可以告诉我如何实现吗?
Can someone tell me how to achieve this ?
在此先感谢,
迈克
Many thanks in advance,
Mike
推荐答案
您可以使用 preg_match_all
提取 id
和 count
值,然后提取 count
和 sum
:
You could use preg_match_all
to extract the id
and count
values and then count
and sum
them:
$cookie = '101(2)_102(3)_103(5)';
preg_match_all('/(?<=^|_)([^(]+)\((\d+)\)(?=_|$)/', $cookie, $matches);
$ids = $matches[1];
$counts = $matches[2];
echo "Total IDs: " . count($ids) . ", total count: " . array_sum($counts);
输出:
Total IDs: 3, total count: 10
请注意,可能会发现用 id
值索引的计数数组更有用,您可以使用 array_combine
在 preg_match_all
:
Note that you may find it more useful to have an array of counts indexed by the id
values, for which you can use array_combine
on the output of preg_match_all
:
$counts = array_combine($matches[1], $matches[2]);
echo "Total IDs: " . count($counts) . ", total count: " . array_sum($counts). PHP_EOL;
这篇关于PHP:拆分cookie值并计数部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!