如果密钥以 PHP 中的 X 开头,则删除 cookie

Delete a cookie if the key start by X in PHP

我得到了一些由 XYZ 启动的 cookie,我想在用户访问特定路由时取消设置它们。

所以我编码:

foreach ($_COOKIE as $key => $value)
        if (preg_match('/^XYZ/', $key))
            unset($_COOKIE[$key]);

但是饼干还在。 我真的不明白,因为当我明白的时候:

foreach ($_COOKIE as $key => $value)
        if (preg_match('/^XYZ/', $key))
            echo($_COOKIE[$key]);

...有效。所以我想知道是否可以像上面那样取消设置cookie。

像这样重置 cookie:

setcookie($key,"",time()-3600);

你可以试试这个 -

foreach ($_COOKIE as $key => $value) {
    if (strpos($key, 'XYZ') === 0) { // check if name starts with 'XYZ'
         setcookie($key, "", (time() - 3600) ); // Set the time which already expired
    }
}

preg_match -

if (preg_match('/^XYZ/', $key)) {
     setcookie($key, "", (time() - 3600) );
}