问题
I am a PHP beginner and hope someone here can help me with this.
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.
Example: 101(2)_102(3)_103(5)
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.
My attempt:
print_r(explode("_", $_COOKIE['myCookieName']));
I assume I need to create an array here.
Expected output (example): Total IDs: 3, total count: 10
Can someone tell me how to achieve this ?
Many thanks in advance,
Mike
回答1:
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);
Output:
Total IDs: 3, total count: 10
Demo on 3v4l.org
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;
Demo on 3v4l.org
回答2:
A slightly simpler version that should work as well:
$cookie = '101(2)_102(3)_103(5)';
preg_match_all('/\((\d+)\)/', $cookie, $matches);
[, $counts] = $matches;
echo 'Total IDs: ', count($counts), ', total count: ', array_sum($counts);
Demo: https://3v4l.org/PQ14O
来源:https://stackoverflow.com/questions/58359439/php-split-cookie-value-and-count-parts