Reputation: 13
I want to store a string in a cookie of the form
1.236|2.48|3.574|4.094|
Each number 1-4 correlates to a div and the number after the dot correlates to a property of the div.
What I want to do is for php to examine the cookie and see if there is an entry for div 3 and if there is, remove the number after the dot and replace it by a number I supply and if not, create an entry in the string with the number I supply. So if the string in the cookie was of the form
1.236|2.48|4.094|
Then the php would set it to
1.236|2.48|4.094|3.66|
with 66 being the number supplied by the script.
And if the string in the cookie was of the form
1.236|2.48|3.574|4.094|
then the php would set it to
1.236|2.48|3.66|4.094|
(or just as good would be:
1.236|2.48|4.094|3.66
)
I have used dots and '|' in my example but they are just as placeholders to separate the data, if they can't be used in a cookie then any other random fixed symbol should do.
Any help appreciated. Thanks.
Upvotes: 1
Views: 171
Reputation: 361
$cookieName = 'myCookie';
$newValue = 66;
$newString = preg_replace('/3\.[0-9]+/',"3.$newValue",$_COOKIE[$cookieName]);
if (strpos($newString,'3.'.$newValue) === false) {
$newString .= '3.'.$newValue;
}
setcookie($cookieName,$newString);
Upvotes: 0
Reputation: 137380
Use setcookie()
function (see documentation) to set and $_COOKIE
array (see documentation) to read cookies.
Upvotes: 3